You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

A bit on endianness

Endianness refers to the ordering of bytes in memory that make up a larger chunk of memory.  There's plenty of information on there on wikipedia for example, but here's a quick overview.  Systems are usually either big-endian or little-endian.  Stealing a table from wikipedia:

Endian

First byte
(lowest address)

Middle bytes

Last byte
(highest address)

Notes

big

most significant

...

least significant

Similar to a number written on paper (in Arabic numerals as used in most Western scripts)

little

least significant

...

most significant

Arithmetic calculation order (see carry propagation)

When we write out a number in hex it looks like big-endian.  For example the number 4097 would be written as 0x1001 where the 0x10 is the MSB (most significant byte) and 0x01 is the LSB (least significant byte.  

The systems we are working on are all little endian though, so the number 4097 would be stored as 0x01:0x10 in memory if we saved it as a short.  Saving it as an int would add some 0s for padding in there lie so: 0x01:0x10:0x00:0x00.  

Converting to other formats

Now say we want to send a uint16 (unsigned short) through acomms along with a bunch of other data.  Well probably be constructing a long array or bytes and copying our data into it for transmission, then picking it back out at the other end.  Sticking with our simple uint16, let's look at how we can reconstruct the number given an array of bytes.  

We receive the following array of bytes: 

Unknown macro: {0x01, 0x10}

.  The following code snippet illustrates two ways of converting these two bytes to an unsigned short.  

// method 1 - bitwise operations
unsigned short result1 = (data[0]<<8) + data[1];
cout << result1 << endl;


// method 2 - memcpy
unsigned short result2;
memcpy(&result2, &data[0],2);
cout << result2 << endl;

These two methods will yield different results.  

  • No labels