If you even wanted to know whats the endianness of the device you are running your code on, this article might just help you out.
But, before we hit the code lets see what does the endianness means.
Endianness is basically how the data is mapped between the registers and the memory. Well most of the time it doesn’t matters what our system’s endianness is, but in rare circumstances like when you are porting your perfect code from one platform to another and all of a sudden you start getting some unexplainable bugs, there might be a case that its something related to the endianness.
Well, the good news is there are only two kind of possible endianness; the Big Endian and the Little Endian.
(Of course, some clever engineers have designed bi-endianess as well, but that is just a merge of the two)
Big Endian:
In this format the data is mapped in such a way that the Most Significant Byte is stored at the lowest address.
So, if the memory starts at location A and we have the data as XY, then the memory is mapped as:
A: X
A+1: Y
You see the bigger the end of the data gets the bigger the address gets, thats why I think they named it Big Endian
Little Endian:
This format (as might have guessed), is just the opposite. Here the Least Significant Byte is mapped at the lowest address.
So, the same case will be mapped as:
A: Y
A+1: X
If you need to get more information on endianness, look at this article at wikipedia
Now, for our code we will be using union, yes that should refresh your C lectures at college.
union endian{
short num;
struct {
char one, two;
}chars;
};
If we assign a number to the short it should be split in two bytes, because the union shares same memory between its members.
So, if the short is a 16 bit (or 2 bytes) long and char is 8 bit (or 1 byte long), whatever data we assign to the short and read as the chars will give us the two halves of the short.
Here’s a main program for our testing:
int main(){
union endian te; /*test endianess*/
te.num = 256;
printf("%p: %d\\n%p: %d\\n",&te.chars.one,te.chars.one,&te.chars.two,te.chars.two);
return 0;
}
As, you can see the data I’m setting to the num variable is 256, that is in binary:
00000001 00000000
or
X: 00000001
Y: 00000000
So, if a device is using Big endian style it should map the the first half to the smaller address and the later half to the bigger address, while, the Little endian machine should assign the first half to the bigger address and the later half to the smaller address.
Here’s the output on my machine:
0x7fff5fbff450: 0
0x7fff5fbff451: 1
Which means internally my machine is mapping data as:
0x7fff5fbff450: 00000000 (A: Y)
0x7fff5fbff451: 00000001 (A+1: X)
And its a clear case of Little endian mapping. Now, check out yours!
Share and Enjoy