Saturday, December 5, 2009

Big-Endian or Little-Endian?

1 Big-endian or Little-endian?

Computers store multibyte values in either big-endian or little-endian order.

What does this mean?

Suppose we are on a machine that has two-byte integers. And we do the following:

  int main()
  {
    int i; 
    i = 1;

    ...
    ...
    ...
}

How is the value 1 (or 00000000 00000001) stored in memory?

In what order are the bytes stored?
Memory LocationValue
000Ax00000000
000Bx00000001

Or

This is different
Memory LocationValue
000Ax00000001
000Bx00000000

Little-endian refers to the idea that the least significant byte (that's LSB) is stored in the lower memory location. (Mnemonic: Least-Low-Little)

Big-endian refers to the idea that the most significant byte (that's MSB) is stored in the lower memory location. (Mnemonic: Most-Low-Big)

Can you look at the tables above and identify which is big-endian and which is little-endian?

The first table shows a computer architecture that is big-endian, the second table, little-endian.

2 Determining Endedness

Determining whether or not we are big- or little-endian is not that hard, but your first guess of how to do it, may be wrong. Here's some code.

#include <stdio.h>
int main()
{
  int i, j;
  char *ptr;

  /* Will shifting work? */

  i = 1;
  j = i >> 1;

  if (j == 0){
    printf("Big-endian\n");
  }else{
    printf("Little-endian\n");
  }
/* This tells Big-endian --- but read on! */

  /* Casting gets us to the byte we want */
  i = 1;
  ptr = (char *) &i;

  /* ptr now points to the lower memory address */
  if (*ptr == 1){
    printf("Little-endian\n");
  }else{
    printf("Big-endian\n");
  }
  /* Prints 'Little-endian' --- that's correct */

}

The first attempt didn't work. That's because the shift operators work in a logical fashion, according to a logical representation of bit patterns.

As such, it's impossible to get to the actual layout of the hardware using them.

But by casting the integer to a char, we can get the first byte, and it becomes possible to determine if the machine is big- or little-endian.

No comments:

Post a Comment