I’m confused when I was reading an article about Big/Little Endian.
Code goes below:
#include <iostream>
using namespace std;
int i = 12345678;
int main()
{
char *p = (char*)&i; //line-1
if(*p == 78) //line-2
cout << "little endian" << endl;
if(*p == 12)
cout << "big endian" << endl;
}
Question:
-
In line-1, can I do the conversion using
static_cast<char*>(&i)? -
In line-2, according to the code, if it’s little-endian, then
78is stored in the lowest byte, else12is stored in the lowest byte. But what I think is that,i = 12345678;will be stored in memory in binary.If it’s little-endian, then the last byte of
i‘s binary will be stored in the lowest byte, but what I don’t understand is how can it guarantee that the last byte ofiis78?Just like, if
i = 123;, theni‘s binary is01111011, can it guarantee that in little-endian,23is stored in the lowest byte?
I’d prefer a
reinterpret_cast.Little-endian and big-endian refer to the way bytes, i.e. 8-bit quantities, are stored in memory, not two-decimal quantities. If
ihad the value0x12345678, then you could check for0x78and0x12to determine endianness, since two hex digits correspond to a single byte (on all the hardware that I’ve programmed for).