开发者

a question from careercup about endian

开发者 https://www.devze.com 2023-02-10 00:12 出处:网络
the program is to decide big endian or little endian. This is the answer given in the book: int Test(){

the program is to decide big endian or little endian.

This is the answer given in the book:

int Test(){
    short int word开发者_高级运维 = 0x0001;
    char *byte = (char *) &word;
    return (byte[0] ? BIG:LITTLE);
}

I don't understand this line: char *byte = (char *) &word; Does it mean "pass the address of word into byte"? So, now byte point to word's original address? As I known, short int is 2 bytes. So, does "byte" point to higher address or lower address? Why?

How does this work?


It's just taking the address of word, casting it to a char pointer, and putting it in byte.

At that point, byte will point to the first byte of 2-byte word, and the value of that byte (1 or 0) will tell you if you're on a big or little endian machine.


If we assume short is 2 bytes, then the memory layout look like this on a big endian machine:

MSB        LSB
-------------------
|  0x0   |   0x1  |
-------------------

And like this on a little endian machine

MSB        LSB
-------------------
|  0x1   |   0x0  |
-------------------

That is, the short 0x0001 consists of 2 bytes, one with the value 0, the other with the value 1. On a big endian machine, the least significat byte (0x1 here) is stored in the lower memory address of that short, the most significant byte is stored in the higher address. On a little endian machine, it's the other way around.

So, char *byte = (char *) &word; gets the address of word and interprets that as a char*. Assuming a char is 8 bits, we now have a pointer to the least significant byte within our short. If that's 0x1, the machine is big endian, as per the diagram above. If it's 0, it's a little endian machine.

(note that this way of checking for endianess might not be portable - e.g. there machines where a char is the same size as a short, and many other more or less esoteric gotchas with this approach)


You want to read word by steps of a single byte. So you take a pointer to word which will look to a byte at a time. This is a char*, since a char is 1 byte by standard definition. Then you point your char* to the location of memory where word was allocated, and read the first value (byte[0], you could have also used *byte to dereference it). If it is 1, it is a big endian machine:

01 00

If it is zero, it is a little endian machine

00 01
0

精彩评论

暂无评论...
验证码 换一张
取 消