Little endian vs. big endian

This is about how the bytes of a data type are arranged in memory. An int variable for example occupies 4 bytes in memory. In case of little endian, the least significant byte of the integer value will be first in memory (at a smaller address). In case of big endian, the most significant byte if the integer value will be the first byte in memory.

Consider the following code that prints the digits of a number by remembering the last digit and by shifting to the left. ‘size’ is the number of bits to print, ‘val’ is the number to print:

void PrintBinary(int val, int size)
{
unsigned char* b  = new unsigned char[size];
memset(b, 0, size);
int pos = size – 1;
while ( val != 0 )
{
b[pos] = val % 2;
val = val >> 1;
pos–;
if (pos < 0) break;
}
for (pos = 0; pos< size; ++pos)
{
printf(“%d”, b[pos]);
if (pos%8 == 7) printf(” “);
}
delete[] b;
}
 
int x = 8;
PrintBinary(x, 32);

Then the above code will print:  00000000 00000000 00000000 00001000

The code below will print ‘00001000 00000000 00000000 00000000’ which  shows that it was run on a little endian machine because the least significant byte is first.

unsigned char* b = (unsigned char*) &x;
for (int i = 0; i
{
 PrintBinary(b[i], 8);
}

Here is a method to determine the endianess of a machine:

bool IsLittleEndian()
{
int b = 1;
return ((unsigned char*)(&b))[0];
}

A more interesting approach is to use a union (a C++ facility to agregate mode data types over the same memory space):

bool IsLittleEndian()
{
union local_t
{
int i;
unsigned char b;
};
local_t u;
u.i = 1;
return u.b;
}
 

That was the C++ approach. Java offers an API for it:

import java.nio.ByteOrder;

if (ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN)) {
System.out.println(“Big-endian”);
} else {
System.out.println(“Little-endian”);
}
 

In C# the BitConverter class has the IsLittleEndian static method.

Advertisements
This entry was posted in c++. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s