Changing Byte Order Using Bitwise Operations

Learn about an application of bitwise operations known as "byte order conversion".

We'll cover the following

Endianness

Bitwise operations are widely used in system programming. The specialists of this domain deal with computer networks, device drivers, and OS kernels. Translating data from one format to another is a common operation in these domains.

To understand these types of data translation, let’s suppose we want to write a driver for some peripheral device. The byte order on the device is big-endian. Our computer uses another order, which is little-endian.

Endianness is the byte order the computer uses to store numbers in memory. The CPU defines the supported endianness. There are two commonly used options today: big-endian and little-endian. Some CPUs support both (bi-endian). Here is an example of how we’d store a four-byte number, 0x0A0B0C0D, for different orders:

0A 0B 0C 0D     big-endian
0D 0C 0B 0A     little-endian

The device sends an unsigned integer to the computer. It equals 0xAABB in hexadecimal. Due to the different byte orders, our computer cannot handle the integer as it is. We need to convert it to 0xBBAA to allow the computer to read it correctly.

Here are the steps for converting the 0xAABB integer to the computer’s byte order:

  1. Read the lowest (rightmost) byte of the integer and shift it to the left by eight bits, i.e. one byte. The following Bash command does that:

    little=$(((0xAABB & 0x00FF) << 8))
    
  2. Read the highest (leftmost) byte of the number and shift it to the right by eight bits. Here is the corresponding command:

    big=$(((0xAABB & 0xFF00) >> 8))
    
  3. Combine the highest and lowest bytes with the bitwise OR this way:

    result=$((little | big))
    

Bash wrote the conversion result to the result variable. It is equal to 0xBBAA.

We can replace all three steps by the single Bash command:

value=0xAABB
result=$(( ((value & 0x00FF) << 8) | ((value & 0xFF00) >> 8) ))
echo $result

Run the commands discussed in this lesson in the terminal below.

Get hands-on with 1200+ tech skills courses.