Tuesday 8 November 2011

How are 16- and 32-bit numbers stored? in C programming

How are 16- and 32-bit numbers stored?

A 16-bit number takes two bytes of storage, a most significant byte and a least significant byte. The preceding
FAQ (X.5) explains which byte is which. If you write the 16-bit number on paper, you would start with the
most significant byte and end with the least significant byte. There is no convention for which order to store
them in memory, however.

Let’s call the most significant byte M and the least significant byte L. There are two possible ways to store these bytes in memory. You could store M first, followed by L, or L first, followed by M. Storing byte M first
in memory is called “forward” or “big-endian” byte ordering. The term big endian comes from the fact that the “big end” of the number comes first, and it is also a reference to the book Gulliver’s Travels, in which the
term refers to people who eat their boiled eggs with the big end on top.

Storing byte L first is called “reverse” or “little-endian” byte ordering. Most machines store data in a bigendian
format. Intel CPUs store data in a little-endian format, however, which can be confusing when someone is trying to connect an Intel microprocessor-based machine to anything else.

A 32-bit number takes four bytes of storage. Let’s call them Mm, Ml, Lm, and Ll in decreasing order of significance. There are 4! (4 factorial, or 24) different ways in which these bytes can be ordered. Over the
years, computer designers have used just about all 24 ways. The most popular two ways in use today, however,

are (Mm, Ml, Lm, Ll), which is big-endian, and (Ll, Lm, Ml, Mm), which is little-endian. As with 16-bit numbers,

most machines store 32-bit numbers in a big-endian format, but Intel machines store 32-bit numbers in a
little-endian format.

Cross Reference:

X.5: What is meant by high-order and low-order bytes?

No comments:

Post a Comment