github twitter email rss
Byte ordering, Endianness
0001 Jun 1
One minute read

Byte ordering, Endianness

struct {
    UInt32 int1;
    UInt32  int2;
} aStruct;

ExampleStruct   aStruct;
aStruct.int1 = 0x01020304;
aStruct.int2 = 0x05060708;

big-endian processor or memory system.
fields are stored with the more significant bytes to the left and less significant bytes to the right.

Figure 1

little-endian system.
lowest address of each field now corresponds to the least significant byte instead of the most significant byte.

Figure 2

Now suppose the example data values initialized by the code shown in Listing 2 are generated on a little-endian system and saved to disk. Assume that the data is written to disk in byte-address order. When read from disk by a big-endian system, the data would again be laid out in memory as illustrated in Figure 2. The problem is that the data is still in little-endian byte order even though it is being interpreted on a big-endian system. This difference causes the values to be evaluated incorrectly. In this example, the decimal value of the field Int1 should be 16909060, but because of the incorrect byte ordering it is evaluated as 67305985. This phenomenon is called byte swapping and occurs when data in one endian format is read by a system that uses the other endian format.

Back to posts

comments powered by Disqus