Masking, bit-shifting and & 0xff00

If you are reading about endian (big and small) and seen snippets of code where you AND the input with 0xff00 and then shift the result say by 8 via >> 8 and wondering what the heck is going on then you’ve come to the right place.

If you have an input such as int = 553, this is represented in binary as 00000010 00101001. I’ve padded some zero’s in and put a space to show how it is represented as 2 bytes. ie 16 bits. If you want to swap the 2 bytes around like this 00101001 00000010, you need to use bit operators and masking and this is the neat part.

Part 1 – Masking

You take the 2 byte input and take a mask of 0xff00 which in binary is: 11111111 00000000 and AND them together.

00000010 00101001
11111111 00000000    (AND)
————————–
00000010 00000000

This basically preserves the first byte. You then shift the result to the right 8 places or 8 bits.
00000000 00000010

and there you have it. Now you do the same with the second byte with a slightly different mask. 0x00ff

00000010 00101001
00000000  11111111 (AND)
————————–
00000000 00101001

and then, you guessed it, shift it left 8 places via << 8.

00101001 00000000

Finally you OR the results:

00000010 00000000
00000000 00101001  (OR)
—————————–
00000010 00101001

and now you have the bytes reversed. It is pretty cool. If you convert it back to decimal, you get 10498.

Wanna see this in action in c code?

 

#include 
#include 

void main () {
   uint16_t x = 553, hi, lo, result;
   printf("%i\n", x);
   hi = (x & 0xff00) >> 8;
   lo = (x & 0x00ff) << 8;
   result = (lo | hi);
   printf("%i\n", result);
}

 

One thought on “Masking, bit-shifting and & 0xff00”

Leave a Reply

Your email address will not be published. Required fields are marked *