Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a char array differ in ordering in a little endian or big endian system

Tags:

c

endianness

I have an array char c[12] = {'a','b','c','d','e','f','g','h','0','1','2','3'} In hexadecimal these values would be {0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x30, 0x31, 0x32, 0x33}

What I was wondering is whether the array would be stored in memory differently in a big endian or little endian system?

I thought that they would be the same because the endian systems work by determining how to store an element by the least or most significant bits of a single element in the array and sorts the bytes, but since a char is just a single byte they order the bytes the same way.

like image 413
MichaelGofron Avatar asked Oct 20 '14 00:10

MichaelGofron


2 Answers

Think about what "big endian" and "little endian" means.

Memory is a sequence (or on more interesting machines, several sequences) of bytes. For items that are two or more bytes in size, the bytes of the item can be stored in memory in different orders, and the two most obvious orders are called "big endian" and "little endian" (if you have three or more bytes, then there are more than two possible byte orders, and anyway, who says that the bits of an int for example cannot be distributed over multiple bytes in a chaotic, but fixed order? )

But for a sequence of bytes, the order of the bytes is the order of the bytes. "Big endian" and "little endian" is defined by the way that the bits of a larger item are arranged in an array of bytes. For a sequence of bytes, they are stored in the order they are stored - there is no possibility of any other order. It's like asking "could the numbers 1, 2, 3, 4 be anything different than the numbers 1, 2, 3, 4? " and of course they can't.

like image 152
gnasher729 Avatar answered Sep 29 '22 09:09

gnasher729


The char/byte is, by definition, the smallest addressable unit of memory. Consequently, there is no meaningful concept of "endianness" within a single byte, because the processor cannot index inside it; it can only read the whole thing. Individual bits from within a byte are obtained by mathematical operations, not by addressing; their physical location has nothing to do with how they're read. Endianness only refers to multi-byte objects that have indexable, and thus physically-ordered, subcomponents.

By definition an array has elements in only one order, otherwise indexing operations would fail, so the machine's notions of endianness for larger types that could hypothetically occupy the same space are not relevant to it either, as they would destroy the array's access rules.

like image 43
Leushenko Avatar answered Sep 29 '22 10:09

Leushenko