Learn Computer Science programming - C# and C++ Algorithms

 
Endianness

In human languages, some are read and written from left to right; others from right to left. The same concept holds true in computer systems. Endianness is the attribute of a system that indicates whether integers are represented from left to right or right to left. Endianness must be taken into consideration at design time.

Big endian the most significant byte of any multibyte data field is stored at the lowest memory address, which is also the address of the larger field.

Little endian means that the least significant byte of any multibyte data field is stored at the lowest memory address, which is also the address of the larger field.

Here is an example of a Big Endian: Examine the bits in this byte. The least significant bit is number 0 and the most significant bit is number 7:

MSB             LSB
 7 6 5 4 3 2 1 0 

Here is the reverse example of a little Endian.
LSB             MSB
 7 6 5 4 3 2 1 0 


Code
 
Endianness refers to the way the computer store the bytes of a multibyte value. For example and integer maybe made up of four bytes on some machines. These four bytes can be stored in various orders. Most computers nowadays, store the LSB (Least Significant byte) to MSB (Most significant byte). 5A6C. The LSB = 6C and MSB = 5A.

Big-endian machines stores MSB to LSB. Little-endian machines stores LSB to MSB.

To test for this choose and integer and set it's value to 1. The MSB will be 0 and the LSB will be 1. The bit operator will not reveal this because it works on the integer after it has been translated and placed in LSB to MSB order. One easy way to examine each individual byte out of the four different bytes is to treat it as a character. A character is one byte long. You would cast the pointer to the integer as a char * and then this will change the variable value from 4 bytes to 1 bytes revealing the first bytes of an integer. If the byte value is 1 then the machine is little-endian because the LSB is 1 and if the value is 0 then the machine is a Big-endian since the MBS is located at the lowest memory address.

//Returns 1 if the machine is Little-endian. 0 if the machine is Big-endian

int Endianess(void)

{
int testNum;
char *ptr;
testNum=1;
ptr = (char *) &testNum;
return (*ptr); // Returns the byte at the lowest address.
}

//Returns 1 if the machine is Little-endian. 0 if the machine is Big-endian
int Endianess(void)
{
union{
int theInteger;
char singleByte;
}endianTest;
endianTest.theInteger =1;
return endianTest.singleByte; // Returns the byte at the lowest address.
}