Wednesday, June 20, 2012

Big Endian or Little Endian

Write a function to test a system is using Big Endian or Little Endian. For a hex A45C Big Endian, MSB (Most Important Byte) is stored in the lowest address: 1st byte - A4, 2nd byte - 5C Little Endian, LSB (Least Important Byte) is stored in the lowest address: 1st byte - 5C, 2nd byte - A4 Windows, Linux use Little Endian, Mac OS uses Big Endian. Network protocol uses Big Endian, so Big Endian is also called Network Byte.
 
/*
 * check the binary value of first byte of 1,
 * value = 0 -> Big Endian
 * value = 1 -> Little Endian
 */
void endianness(){
    int testNum;
    char* ptr;

    testNum = 1;
    ptr = (char*) &testNum;
    if(*ptr) {
        printf("Little Endian.");
    } else {
        printf("Big Endian.");
    }
}

/*
 * use union, theInteger & singleByte will share the same lowest address
 */
void endiannessV2(){
    union{
        int theInteger;
        char singleByte;
    } endianTest;

    endianTest.theInteger = 1;
    if(endianTest.singleByte) {
        printf("Little Endian.\n");
    } else {
        printf("Big Endian.\n");
    }
}

/*
 * convert from a network byte
 */
int getIntBE(int networkbyte){
    char* ptr = (char*)&networkbyte;
    return (int)(ptr[0]<<24) + (int)(ptr[1] << 16) + (int)(ptr[2] << 8) + (int)(ptr[3]);
}

/*
 * convert to a network byte
 */
int getIntLE(int value){
    char* ptr = (char*)&value;
    return (int)(ptr[3]<<24) + (int)(ptr[2] << 16) + (int)(ptr[1] << 8) + (int)(ptr[0]);
}

No comments:

Post a Comment