Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
531 views
in Technique[技术] by (71.8m points)

c - Little vs Big Endianess: How to interpret the test

So I'm writing a program to test the endianess of a machine and print it. I understand the difference between little and big endian, however, from what I've found online, I don't understand why these tests show the endianess of a machine.

This is what I've found online. What does *(char *)&x mean and how does it equaling one prove that a machine is Little-Endian?

int x = 1;
if (*(char *)&x == 1) {
    printf("Little-Endian
");
} else {
    printf("Big-Endian
");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If we split into different parts:

  1. &x: This gets the address of the location where the variable x is, i.e. &x is a pointer to x. The type is int *.

  2. (char *)&x: This takes the address of x (which is a int *) and converts it to a char *.

  3. *(char *)&x: This dereferences the char * pointed to by &x, i.e. gets the values stored in x.

Now if we go back to x and how the data is stored. On most machines, x is four bytes. Storing 1 in x sets the least significant bit to 1 and the rest to 0. On a little-endian machine this is stored in memory as 0x01 0x00 0x00 0x00, while on a big-endian machine it's stored as 0x00 0x00 0x00 0x01.

What the expression does is get the first of those bytes and check if it's 1 or not.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...