# Thread: Big and little endian

1. ## Big and little endian

Ok, Big and little endians have got me confused.

The number 258, in memory, is (assuming a four-byte integer) 02010000 in hex on a little endian machine, and 00000102 on a big endian machine. Right?

Now, if that's right, is the following portable between big & little endian machines?
Code:
```unsigned int a = 258, x;
// Output each byte of A
for(x = 0; x < 4; x++) printf("%02X\n", (a >> (x * 8)) & 0xFF);```
As in, would that output:
Code:
```02
01
00
00```
On both big and little endian machines? Or will it be reversed on big endian machines?

2. When dealing with values, endianness does not come into play. It is only when you are looking at the underlying storage of a multi-byte object that endianness is seen.

In the code you posted, you are not looking at the underlying storage, you are manipulating a value.

3. In addition to Dave's post, it will make a difference if you do something like:
Code:
```int val = 258;
char bytes[4];

bytes[0] = *(char *)val;
bytes[1] = *((char *)val + 1);
bytes[2] = *((char *)val + 2);
bytes[3] = *((char *)val + 3);```
The bytes array will end up with different values on big and little endian machines. Bit-shifting a 4-byte value makes no difference though, as Dave pointed out.

4. Originally Posted by Cactus_Hugger
Ok, Big and little endians have got me confused.

The number 258, in memory, is (assuming a four-byte integer) 02010000 in hex on a little endian machine, and 00000102 on a big endian machine. Right?
wouldnt that be a 00001020 on big endian? The rest is like Lurking Cat said

5. Originally Posted by blackswan
wouldnt that be a 00001020 on big endian? The rest is like Lurking Cat said
No, endianness refers to byte order. There are two hexadecimal digits to a byte. 02 01 00 00 -> 00 00 00 01 02