Photography and Projects

Bit Masking

Bit Masking and a real world example.

Here I am going to explain how to use and (&) to mask bits in a number using an example.

I have an 8-bit output port with each bit of the port being used for different things. I can set individual bits using the bit identifier e.g. PORTB.B5 = 1; sets bit 5 of port B (RB5) high. However, in my example I am using the first 3 bits together to set an external light controller with each bit signifying a different coloured light. My preference is to set all 3 bits at the same time so the light controller sets only one colour from the 3 bits. If I set each bit one at a time the light controller will cycle through colours as the bits change. This is not desired.

Setting PORTB to something between 0 and 7 will set the bits correctly but it will also change all other bits in Port B to 0. So what I need to do is find out what bits (4-7) are set and make sure these bits remain set after I set the bits for my light controller.

We do this by masking the bits. This is the current setting of Port B:

0110 1010 = 0x6A

If I mask this using 1’s for bits 4-7 I can see which are set:

1111 1000 = 0xF8

Using the mask I get a 1 where the original number and mask are both 1’s and a 0 for all other cases. So 0x6A & 0xF8 = 0x68

0110 1010 (0x6A)
1111 1000 (0xF8)
0110 1000 (0x68)

Now I can set the port using PORTB = 0x68 + 4; 4 being the value I want to set the first 3 bits to.

Using the following statements we can perform all steps. I will use lte as the variable to set the lights:

lte = 4;
PORTB = (PORTB & 0xF8) + lte;

You can also use bit masking to find if an individual bit is set or not. Example, test if bit 4 is high:

You can use: button = PORTB.B4;

You can also do the following bit masking: button = (PORTB & 0x10);

These both return 1 if the bit is set or 0 if the bit is not set.

These examples are based on C language for PIC Microcontrollers. The same can be applied in different languages using a different syntax.
RapidWeaver Icon

Made in England