March 27, 2012

Determining Byte Order (Endianness)

Question: One of the commonly asked question is how will you determine the byte order of the machine using a c program. The byte order can be either little endian or bid endian. 


A little endian system will store the least significant byte of any multibyte data field at the lowest memory address. Example: 
0xaabbccdd will be stored as ddccbbaa
0x00000001  will be stored as 01000000

bool is_little_endian()

{
    int i = 1;
    char *c = (char *)&i;
    return (*c);
}


bool is_little_endian2()
{
    union {
        int i;
        char c;
    } u;


    u.i = 1;
    return(u.c);
}

No comments:

Post a Comment