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:
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.
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 !
printf(“System follows Little Endian \n”);
printf(“System follows Big Endian \n”);
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)
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 ! 🙂