Sunday, July 8, 2007

What Little-Endian and Big-Endian? How can I determine whether a machine's byte order is big-endian or little endian? How can we convert from one to a

First of all, Do you know what Little-Endian and Big-Endian mean?

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


Intel processors use "Little Endian" byte order.


"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.

In "Little Endian" form, code which picks up a 1, 2, 4, or longer byte number proceed in the same way for all formats. They first pick up the lowest order byte at offset 0 and proceed from there. Also, because of the 1:1 relationship between address offset and byte number (offset 0 is byte 0), multiple precision mathematic routines are easy to code. In "Big Endian" form, since the high-order byte comes first, the code can test whether the number is positive or negative by looking at the byte at offset zero. Its not required to know how long the number is, nor does the code have to skip over any bytes to find the byte containing the sign information. The numbers are also stored in the order in which they are printed out, so binary to decimal routines are particularly efficient.


Here is some code to determine what is the type of your machine


int num = 1;
if(*(char *)&num == 1)
{
printf("\nLittle-Endian\n");
}
else
{
printf("Big-Endian\n");
}



And here is some code to convert from one Endian to another.



int myreversefunc(int num)
{
int byte0, byte1, byte2, byte3;

byte0 = (num & x000000FF) >> 0 ;
byte1 = (num & x0000FF00) >> 8 ;
byte2 = (num & x00FF0000) >> 16 ;
byte3 = (num & xFF000000) >> 24 ;

return((byte0 << 24) | (byte1 << 16) | (byte2 << 8) | (byte3 << 0));
}

57 comments:

Anonymous said...

Thanks Vijay..
Good Explaination..
Its easy for me to understand this now...

Anonymous said...

Thanks
explanation is to the point
I couldn't find better explanation than this.

Anonymous said...

Union Solution

An alternative solution also exists where
a union is created of char[4] and int.

Pardon me for not writing exact C code.
unionvar.int_member = 0xABCDEF12 ;

if ( unionvar.char_member[0] == 0xAB )
print Biggie ; // MSB First
else
print little

Ivan Novick said...

For your reverse question it would also be nice if the function was more generic to accept multiple sizes of integer variables like 2, 4 or 8 byte integers:

void reverse(char* variable, unsigned short length){
for (unsigned short i = 0, j= length-1; i < length/2; ++i, --j){
char tmp = variable[i];
variable[i] = variable[j];
variable[j] = tmp;
}
}

sneha said...

nice explaination :)

Vijay Agrawal said...

Thanks guys for appreciating my work!

Scorpion said...

Copied directly from CrackTheInterview pdf file. Shame on you.
Show some creativity once in a while.

Dheeraj said...

@scorpian

dude what creativity you want ???
you give me better explanation than this.
i am sure you wont be able to ...

Ronak said...

unsigned char endian[2] = {1, 0};
short x;

x = *(short *) endian;

if(x==1)
machine is little endian system
if(x==256)
machine is big endian system

I think this may also work

Anonymous said...

Cleonjoys:
@Vijay Your explanation was good and check methods were good.

However i feel this code is simple and gets the desired result:-

#include

int main(){

char *p="12";

if((p - ++p) == -1)
printf("Little endian\n");
else
printf("Big endian\n");

return 0;
}

Anonymous said...

Certainly. I join told all above.

subburajr said...

unsigned long LITTLETOBIG(unsigned long x)
{
return ((x << 24) | ((x << 8) & 0x00ff0000) | ((x >> 8) & 0x0000ff00) | (x >> 24));
}
unsigned long BIGTOLITTLE(unsigned long x)
{
LITTLETOBIG(x);
}

Anonymous said...

Nice explanation dude....

Anonymous said...

short & sweet explanation..
n easy to understand..
thnx

Adeel Chaudary said...

Excellent way to explain.After reading your post i have been able to completely understand the concept of big and little endian.

Anonymous said...

Thanks !

I had an assignment and all the other examples I found were written / documented like crap. Kudos!

Anonymous said...

@ Dheeraj and Vijay
guys its totally wrong to declare someone else work as your..
Direct copy from the book u stupid

Anonymous said...

i would report it to crackthenterview.com
guys .....may be it would make you upside down :D

JABoye47x said...

Thanks so much!!!

saravanan said...

superb

Dhaval said...

Thanks...
Good explanation..

Anonymous said...

CAN U PLZ GIVE ME SOLUTION IN ONE LINE,TO DETERMINE MACHINE'S BYTE ORDER IS BIG ENDIAN & LITTLE ENDIAN?

Anonymous said...

can anyone give a single line code TO DETERMINE MACHINE'S BYTE ORDER IS BIG ENDIAN OR LITTLE ENDIAN?

Anonymous said...

Really nice article...

Anonymous said...

Nice One

Anonymous said...

I tried a lot of places , yours is pretty a neat solution and explanation .... Good work Vijay !

vikas said...

neat.......:)
good job keep going.

Anonymous said...

@ this program
#include

int main(){

char *p="12";

if((p - ++p) == -1)
printf("Little endian\n");
else
printf("Big endian\n");

return 0;
}
in the if statement p refers to address of character 1 and ++p refers to character 2. As character is 1 byte it will always give -1. The correct statement is
if ((*p - *++p)=-1)

HV said...

gr8 work,, thanku so much.. :)

Anonymous said...

Best!! :)

Sourish Jana said...

Well said Vijay. This is proper and helps soooo much. Thanks a lot...

Anonymous said...

I have been taking operating systems class for the whole semester, and finally!! nice to meet you little endian and big endian. Thanks

Anonymous said...

It must have been a lot of effort to copy paste the whole crack the coding interview..

deep said...

According to what you explained, then the output of following code must depend on endianess of the machine:

#include
int main()
{
int x=300;
/* greater than any value that a
signed or an unsigned char can
hold */
char *cptr=(char *)&x;
printf("%d",*cptr);
return 0;
}

In a big endian machine, value will be displayed according to the bit pattern in MSB while in a little endian machine, value will be displayed according to the bit pattern in LSB(300%256).

Is it true?

Anonymous said...

Never knew about the Solaris processors. ;-)

PRAVIN said...

nicely explained...............thanks.

Anonymous said...

http://www.ritambhara.in/big-and-little-endian/

Anonymous said...


@ Anonymous said...

i agree for your solution but it is totally compiler dependent means this method may drop SIDE_EFFECT.

Anonymous said...

Good Explanation .. thanks

Anonymous said...

I would say say that the number of people take, as there are
stars in that ring. 'Salep, sometimes spelt salop, was available from the seventeenth century onwards in English coffee houses, together with other fashionable Ottoman beverages such as coffee and sherbet. The researchers discovered that farmacia on line has sponsored. They make twenty toes.

My web site :: Www.embrace.co.uk

Anonymous said...

Fireside Stories in Hawai'i Volcanoes National Park. 6million 81 per cent of all Polly Peck's cash balances was
held by its Turkish and Northern paphos car hire companies.
Alternatively you can use for my paphos car hire.

However, while paphos car hire joined the
fray 7 years later. We generally complete this in about 45 minutes to put
together. 5 knots It is a bad day to have your car.
These problems can make the trip downtown.
Hmm but the execution leaves much to be desired. I couldn't be happier to tell people that.

Also visit my website: paphos car hire comparison

Anonymous said...

What ever be your choice The real Farmacia On Line or Generic Farmacia On Line Online according to
the researchers, because the infants are preventing the females
from bearing new young. All the junk mail directs
me to the same nationally respected Pharm. HardwareThe Play Book is expected
to do.

Here is my web blog - za.57883.net

Anonymous said...

As a result, farmacia on line has met the medical needs of a group of
women who talked with doctors about sexual dysfunction in women.
If you have an urgent question or need to discuss your concerns privately with Gather's support staff, you can take Sublingual Ciali. But, the lack of third-party backgrounding for applications. The majority of sperm reacts on this exposure and will therefore be affected by the Farmacia On Line.

my blog post :: http://www.hisociety.jp/

Anonymous said...

I am glad I did as the week before again booking through Tipoa paphos car hire, I was delighted.
Guests can also hire them with appropriate in-service training and a supportive environment.

Anonymous said...

Therefore, bilingualism is a complex issue where research is still ongoing
and the limited number of long term paphos car hire offers rental
agreements from just 28 days through to as long as you wish.


my weblog :: gemini-soft.co.kr

Anonymous said...

If you arrive at the Sunshine Coast You can head on back to your hotel location.
But seeing these surrounding regions definitely require a paphos car hire company, which offers considerable savings.
We believe One Night with the Bentley GTC or Bentley Flying Spur will change
your outlook on life'. We have the largest fleet of rental cars that meet your specifications.

my web page www.sitetrail.com

Anonymous said...

Hey there! This is my 1st comment here so I just wanted to give
a quick shout out and say I genuinely enjoy reading through your posts.
Can you suggest any other blogs/websites/forums that cover the same topics?
Many thanks!

my web page :: bmr calculator to lose weight

Anonymous said...

This iѕ the right blog foг еverуone
whο ωishеs to find οut about this tοpic.
You unԁerstand so much its almost hard tο argue with you
(nоt that I personally wіll need tо…HaHa).
You defіnіtely put a new spіn on a subject that's been discussed for decades. Wonderful stuff, just wonderful!

My blog post DiamondLinks

Anonymous said...

Callers we spoke to reps, they told me to us drugconnectionrx farmacia on line.
For calls, the earpiece was loud and crystal clear, and in the milk protein casein.
My favorite part of the same color.

Feel free to surf to my site; see this here

Anonymous said...

Obvious actions, like a silent conversation with a chief in his 60s
who had four younger wives, a CIA officer, saw an opportunity, and reached the conclusion that you can't go wrong with this product. Dr Jackson had warned of buying farmacia on line this way: you can never be sure you've got
plenty of juice to get you to your notification window on the
phone at all. One of the first drugs shown
to have positive effects on the heart.

my blog post - visit this website

Anonymous said...

Inform the paphos car hire company in Cuba, and provided us with
a decent routine, leading to pressure along with making the holiday break to adopt inside a
number of airports. If you are interested in visiting Lara Bay, home to a large underground cavern,
that contains a single driver. Wheels Direct2 U allows you
to carve out a portion of the costs to the council's Trading Standards Service. Follow the beach road, you discover the real essence of a place for itself in one trip.

Stop by my page ... car rental paphos international airport

Anonymous said...

Awesome Job!!

Anonymous said...

Hi Vijay,
What's your reasoning behind "*(char *)&num"? I "sort of" get it but I don't think it would help me very much by "kind of" knowing things.

If you want to do "*(char *)&num" why not declare "num" as a char instead of an int?

Any detail explanation of your logic is greatly appreciated.

Abinaya said...

Hi Vijay,

Please walk me through your code which determines the system being big endian or little endian.

Couldn't get it.

Blogger said...

There's shocking news in the sports betting world.

It's been said that any bettor needs to see this,

Watch this now or stop placing bets on sports...

Sports Cash System - Advanced Sports Betting Software.

yanmaneee said...

lebron 16
adidas tubular
adidas tubular
jordan shoes
cheap jordans
hogan outlet online
coach outlet sale
nike sneakers for women
louboutin shoes uk
nike air max 2019

erectile dysfunction medications said...

Asking questions are truly pleasant thing if you are not understanding anything entirely, except this paragraph provides nice understanding yet.