问题
I heard in little endian, the LSB is at starting address and in Big endian MSB is at starting address. SO I wrote my code like this. If not why ?
void checkEndianess()
{
int i = 1;
char c = (char)i;
if(c)
cout<<"Little Endian"<<endl;
else
cout<<"Big Endian"<<endl;
}
回答1:
No, you're taking an int and are casting it to a char, which is a high-level concept (and will internally most likely be done in registers). That has nothing to do with endianness, which is a concept that mostly pertains to memory.
You're probably looking for this:
int i = 1;
char c = *(char *) &i;
if (c) {
cout << "Little endian" << endl;
} else {
cout << "Big endian" << endl;
}
回答2:
An (arguably, of course ;-P) cleaner way to get distinct interpretations of the same memory is to use a union:
#include <iostream>
int main()
{
union
{
int i;
char c;
} x;
x.i = 1;
std::cout << (int)x.c << '\n';
}
BTW / there are more variations of endianness than just big and little. :-)
回答3:
Try this instead:
int i = 1;
if (*(char *)&i)
little endian
else
big endian
来源:https://stackoverflow.com/questions/3572371/does-this-code-check-for-endianess