Reputation: 11911
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;
}
Upvotes: 3
Views: 372
Reputation: 77762
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;
}
Upvotes: 11
Reputation: 106246
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. :-)
Upvotes: 2
Reputation: 118710
Try this instead:
int i = 1;
if (*(char *)&i)
little endian
else
big endian
Upvotes: 1