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:

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

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

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

    ReplyDelete
  4. 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;
    }
    }

    ReplyDelete
  5. Thanks guys for appreciating my work!

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

    ReplyDelete
  7. @scorpian

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

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

    ReplyDelete
  9. 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;
    }

    ReplyDelete
  10. Certainly. I join told all above.

    ReplyDelete
  11. 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);
    }

    ReplyDelete
  12. Nice explanation dude....

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

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

    ReplyDelete
  15. Thanks !

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

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

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

    ReplyDelete
  18. Thanks...
    Good explanation..

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

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

    ReplyDelete
  21. Really nice article...

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

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

    ReplyDelete
  24. @ 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)

    ReplyDelete
  25. gr8 work,, thanku so much.. :)

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

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

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

    ReplyDelete
  29. 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?

    ReplyDelete
  30. Never knew about the Solaris processors. ;-)

    ReplyDelete
  31. nicely explained...............thanks.

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

    ReplyDelete

  33. @ Anonymous said...

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

    ReplyDelete
  34. Good Explanation .. thanks

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

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

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

    ReplyDelete
  38. 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/

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

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

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

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

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

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

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

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

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

    ReplyDelete
  48. Hi Vijay,

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

    Couldn't get it.

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

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

    ReplyDelete