Reputation: 81
I know that the most common method to test endianity programmatically is to cast to char* like this:
short temp = 0x1234;
char* tempChar = (char*)&temp;
But can it be done by casting to short* like this:
unsigned char test[2] = {1,0};
if ( *(short *)test == 1)
//Little-Endian
else
//Big-Endian
Am I right that the "test" buffer will be saved (on x86 platforms) in the memory using Little-Endian convention (from right-to-left: "0" at lower address, "1" at higher) just like in case with the "temp" var?
And more generally if I have a string: char tab[] = "abcdef"; How would it be stored in the memory? Will it be reversed like: "fedcba"?
Thx. in advance:-)
PS.
Is there any way to see how exactly the data of a program look like in the system memory?. I would like to see that byte-swap in Little-Endian in "real life".
Upvotes: 0
Views: 628
Reputation: 3393
Both ways are not guaranteed to work, furthermore, latter invokes undefined behavior.
First fails if sizeof(char) == sizeof(short)
.
Second may fail for the same reason, and is also unsafe: result of the pointer cast may have wrong alignment for short, and accessing the (short) value invokes undefined behavior (3.10.15).
But yes, the char buffer is stored sequentially into memory so that &test[0] < &test[1]
,
and more generally, as others have already said, char tab[] = "abcdef"
is not reversed or otherwise permuted regardless of endianness.
Upvotes: 0
Reputation: 2196
Your alternative method for checking endianness would work.
char tab[] = "abcdef"
would be stored in that same order: abcdef
Endianness comes into play when you access multiple bytes (short, int, and so on). When you try to access tab[]
as a short array using a little endian machine, you'd read it as ba, dc, fe (whatever their actual byte equivalents are, this is the order the chars are "evaluated" in the short).
Upvotes: 0
Reputation: 272467
Your code would probably work in practice (you could have just tried it!). However, technically, it invokes undefined behaviour; the standard doesn't allow you to access a char array through a pointer of another type.
And more generally if I have a string: char tab[] = "abcdef"; How would it be stored in the memory? Will it be reversed like: "fedcba"?
No. Otherwise tab[0]
would give you f
.
Upvotes: 2