Bit Masking

If we have a binary value in a program, which can be any program not necessarily a microcontroller and only want to change certian bits, we can with bit masking.

A binary number is made up of 1s and 0s, so a value of 0 is 00000000 and 255 is 11111111 (we are only using 8 bit here, so 8 1s or 0s) If I’m sharing an output port or shift register and can only address it with an 8 bit number, if I want to add or remove only certain bits then we use bit masking with binary.

I use this instead of digital.write in the Arduino platform, it works inside that IDE and with other microcontrollers such as PIC. It’s well worth knowing about.

The following examples I find useful when programming.

Switches OFF Port A0 and A1:
PORTA = (PORTA & ~B00000011);

Switches ON Port A0 and A1
PORTA = (PORTA & ~B00000011) | 3;

Lets say now we hold the output data in a variable called ‘data’ e.g for a shift register I would shift out the varialbe value.

Clears bit 5 to 7 and adds bit 5 (value 32)
data = (data & ~B11100000) | 32;

Adds bit 5 but doesn’t clear it first
data = data | 32;

Clears bit 5
data = (data & ~B00100000);

The adding/clearing of bits is the most useful. This is invaluable when it comes to shift registers or sharing ports

A useful online tool to test bit masking can be found here