tags:

views:

139

answers:

3

Hi

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;


}
+10  A: 

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;
}
EboMike
@EboMike Thank you very much. Can u pls explain what the "high level concept means here". I am doing the same right. I will get the first byte value of int when I cast it to a char right?
mousey
High-level concept means that casting is part of the C/C++ language and is clearly defined in the standards, and as such the result is predictable on every possible platform you're running your code on. Endianness is a property of your CPU, i.e. this is part of the assembly language. Since this is platform-dependent, it's something C/C++ is trying to hide from you so you don't have to write platform-specific code. By writing to memory and then reading from it (by using pointers), you're doing something a lot closer to the hardware and as such can test for endianness.
EboMike
`char` and `int` are both integral types. The cast from `int` to `char` narrows the type, but has a well-defined meaning that attempts to preserve `int` values that happen to fit in a `char`. That way `(char)42` still has the value 42...
RBerteig
+1  A: 

Try this instead:

int i = 1;
if (*(char *)&i)
    little endian
else
    big endian
Matt Joiner
+2  A: 

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. :-)

Tony