0

Possible Duplicate:
Detecting endianness programmatically in a C++ program

I'm trying to check if I'm running a little or big endian OS.

int main()
{
    int i = 1; 
    unsigned char b = i; 
    char *c = reinterpret_cast<char*>(&i); // line 5

    cout << "Processor identified as: " << endl;

    if (*c == b) 
        cout << "Little endian" << endl;
    else
        cout << "Big endian" << endl;
}

I'm not sure if casting an int* to char* pointer in line 5 is guaranteed to return a lowest address. Am I doing it right?

Community
  • 1
  • 1
user103214
  • 3,478
  • 6
  • 26
  • 37

3 Answers3

0

It might give you the bottom address of the call stack (of the main thread).

But heap addresses may compare lower (or upper) to that address.

Also, stack growth direction is orthogonoal to endianess.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
0

The C++ standard does not place any restrictions on the byte content of an integer. You may find some systems that are neither little nor big endian - eg, the PDP-11 used a format in which 0x0A0B0C0D was stored as 0B 0A 0D 0C. It's also allowed for there not to be any 0x01 byte at all in the representation for 1.

As for whether the cast will return the lowest byte in the int, it will. However, again, the content of this byte is not well-defined by the C++ specification.

bdonlan
  • 224,562
  • 31
  • 268
  • 324
0

Your char will have the same address as your int, which will be the lowest address of any byte in the int. In don't know if this is actually guaranteed, but it's true on every system I've ever used.

John Gordon
  • 2,576
  • 3
  • 24
  • 29