Question

Question related to little endian and big endian:

unsigned int i = 0x12345678; // assuming int is 4 bytes.
unsigned char* pc = &i;

Now, if *pc is 12 that means it is BIG ENDIAN because lowest address is storing MSB and if 78 Little. Is my understanding correct?

If yes, then my question is, why pc will get the lowest address of i? How does it works? Also, how many memory addresses will be needed to store i?

Assume a 32 bit Architecture

Was it helpful?

Solution

Any variable will be identified by a single address, regardless of the size of the type.

If int i is stored at address 0x1f00, it takes up the four bytes 0x1f00, 0x1f01, 0x1f02 and 0x1f03 of space. Still, when you create a reference to it, you will get the start address only, because the size is implied by the type.

So when you create a reference to an int and cast it to a char reference, you don't change the address, you simply tell the compiler to treat it as a char instead. I.e. the address is still 0x1f00, and when you dereference it you will read whatever is stored there, which is like you say MSB for little endian and LSB for big endian machines.

OTHER TIPS

  1. Yes; your understanding is correct.

  2. Because that is the way C works, and because it makes sense. The address of i is the starting byte followed by 3 other bytes (in the 32-bit architecture). That is, given the starting address and the size, the bytes where the value is stored is &i+0, &i+1, &i+2 and &i+3 (rather than &i-0, &i-1, &i-2 and &i-3 which you seem to think might make some sense).

For most practical purposes, it really makes very little difference, so it really isn't something to sweat over. As long as the hardware is self-consistent, all works OK. There were (still are) some chips that could be switched from big-endian to little-endian at run-time.

int i = 0X01234567; // int occupies 4 bytes
            Address in the increasing order
        --------------------------------------->
+----------+-----------+-----------+----------+----------+
| 0013FF59 | 0013FF60  | 0013FF61  |0013FF62  | 0013FF63 |
+----------+-----------+-----------+----------+----------+
|          |   67      |   45      |   23     |    01    |
+----------+-----------+-----------+----------+----------+

why pc will get the lowest address of i? How does it works? 

when you say

unsigned char* pc = &i;

pc gets the lowest address. and when you say int j = *pc, the system knows, int occupies 4 bytes and it is little endian. It knows how to get the number from the address stored in pc.

Also, how many memory addresses will be needed to store i?

On your system 4 memory locations are need to store i. And the access i, 1 memory address is enough.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top