Tag Archives: little endian

Little-Endianism and Big-Endianism , know what your system follow !!!

Hello friends ,

This is not a new thing for most of you , but still I am trying to enlighten this topic .

I’ll focus mainly on two things –

1.How can I determine whether a machine’s byte order is big-endian or little endian?
2. How can we convert from one to another?

For above queries , first you need to know Little Endian and Big Endian .

Little Endian means that the lower order byte of the number is stored in memory at the lowest address, and the higher order byte is stored at the highest address. That is, the little end comes first.

For example, a 4 byte, 32-bit integer
Byte3 Byte2 Byte1 Byte0
will be arranged in memory as follows:

Base_Address+0 Byte0
Base_Address+1 Byte1
Base_Address+2 Byte2
Base_Address+3 Byte3

Here base address may be any valid address of location .

Intel processors use “Little Endian” byte order. That’s why most of us use little endian systems .

Big Endian means that the higher order byte of the number is stored in memory at the lowest address, and the lower order byte at the highest address. The big end comes first.

Base_Address+0 Byte3
Base_Address+1 Byte2
Base_Address+2 Byte1
Base_Address+3 Byte0

Motorola, Solaris processors use “Big Endian” byte order.

Now with the help of following code you can find out that which endianism your system follow !

int main()
{
int num=1;
if(*(char *)&num==1)
printf(“System follows Little Endian \n”);
else
printf(“System follows Big Endian \n”);

return 0;

}

So friends run this code on your machine .

Now for second query we have a function which converts a number from one endian to another .

And here we go –

int convert_endian(int a)
{
int byte0,byte1,byte2,byte3;
byte0=(a & 0x000000ff)>>0;
byte1=(a & 0x0000ff00)>>8;
byte2=(a & 0x00ff0000)>>16;
byte3=(a & 0xff000000)>>24;
return (byte0<<24 | byte1<<16|byte2<<8|byte3<<0);
}

The explanation of this code –

Code assumes 32 bit architecture and store all the bytes (4 in number) into separate temporary integers .. also ensure to have all the 8-bits are at their LSB’s
now return the number formed by concatenating of byte’s in reverse order .. this has been achieved in the code by ORing the various bytes shifted to the appropriate positions.

Hope this will help you to know your system better ! 🙂

Leave a comment

Filed under Tech-Bowl