user2999521
user2999521

Reputation: 1

C detecting endianess Example

I did not understand the example bellow given by some guy in another question about endianess detection. The number set to "bint" should be 0x10203040 and not 0x01020304. Right?

int is_big_endian(void)
{
    union {
        uint32_t i;
        char c[4];
    } bint = {0x01020304};

    return bint.c[0] == 1; 
}

Upvotes: 0

Views: 399

Answers (2)

shf301
shf301

Reputation: 31394

On a big endian machine the bytes (not nibbles) in an integer are laid out in memory with the top byte of the integer at the lowest memory address so the layout of c on a big endian machine would be:

c[0] = 0x01;
c[1] = 0x02;
c[2] = 0x03;
c[3] = 0x04;

On a little endian machine the bytes are laid out in the opposite orders, with the lowest by of the integer at the lowest memory address. So on a little endian machine c would be laid out as:

c[0] = 0x04;
c[1] = 0x03;
c[2] = 0x02;
c[3] = 0x01;

Upvotes: 1

Paul92
Paul92

Reputation: 9062

If the machine is little endian, the number will be stored as 04 02 03 01, while in big endian, it will be 01 02 03 04 . Note that when talking about endiannes, you talk about BYTE order, which in hexadecimal is 2 digits.

As this example may not be clear for you, let's take a better example: 0x12345678. In big endian, it is stored like 12 34 56 78, while in little endian is stored like 78 56 34 12.

Note that in my memory representation (like 01 02 03 04, for example), the adresses grow from left to right.

Upvotes: 0

Related Questions