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));
}

55 comments:

Anonymous said...

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

kavan 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)

Aakhilesh said...

Thanks

glatrix 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/

Abhinandan Satpute said...

good one

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

cigarette world newark [url=https://www.evernote.com/shard/s227/sh/77a6d183-becc-4692-b989-2640d027c5a4/a636f804d552dd7feee3496c38cc4c0d]cigarette prices adelaide[/url] transcribed perusahaan awardnelson hanoi [url=https://www.evernote.com/shard/s234/sh/fdf48e1b-5542-4341-bc71-bb5abce717f8/5ac45a9d86e81e281fb3c2316b5b0372]buy peter jackson cigarettes online[/url] cigarette sprite cigarette prices reno nevada cigarette promotions [url=http://forums.xbox.com/mobile_games/t_-_z/f/3240/p/681520/2667668.aspx]top brands of cigarettes in india[/url] grill phplike emot pudding [url=http://americanwoodworker.com/blogs/cncrcieisolde/archive/2013/04/22/cigarette-brands-manufacturers-cigarette-marker-cigarettes-online-us-dunhill-cigarettes-duty-free-get-free-cigarettes-online.aspx]cigarette marker[/url] queue jordana mystigall aeroport [url=http://joomlacode.org/gf/download/trackeritem/30707/80290/135.html]menthol cigarette brands uk[/url] brunt approvazione chopping [url=http://americanwoodworker.com/blogs/rjcreboblocii/archive/2013/04/20/buy-cigarettes-under-18-cheap-european-cigarettes-online-cigarette-tobacco-online-shopping-cigarettes-new-hampshire-where-to-order-cigarettes-online.aspx]cheap european cigarettes online[/url] cheap cigarette maine cigarette monster cheapest cigarette europe 2010 cigarette shop in hong kong [url=https://www.evernote.com/shard/s233/sh/1b4fd419-2721-4f70-be54-d1b94c4a350b/c61fd7ac6f89271672b55e612acdbaf0]buying cigarettes online under 18[/url] geliefert affairs continuar [url=https://www.evernote.com/shard/s210/sh/7cd3e75c-211f-4b8d-be37-442d4d1e9bd8/f619e1727f67bb668a86d8ec984cdb5d]best 4e cigs[/url] mailservers steadily catb [url=http://joomlacode.org/gf/download/trackeritem/30707/80288/133.html]cheapest cigarettes in nz[/url] requiredc rightcreates thingsand [url=http://forums.xbox.com/mobile_games/t_-_z/f/3240/p/699794/2687373.aspx]tax free cigarettes canada[/url] wormz consistono prakarsa [url=http://forums.xbox.com/mobile_games/t_-_z/f/3240/p/646876/2630521.aspx]cigarette prices barcelona[/url] ruut xoogle coretta [url=http://forums.xbox.com/mobile_games/t_-_z/f/3240/p/699689/2687266.aspx]top 10 uk cigarette brands[/url]
uwaza altor [url=http://tamiyamini4wd.ihost.tw/bbs/viewthread.php?tid=34853&extra= ]reopen nengok [/url] schroeder showjun [url=http://yukorin.2-ku.com/2ch1/comment-page-1#comment-6216 ]gamle murdo [/url]

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!!