Arduino Bit Masks and Bitwise Operations

A bit mask (or bitmask) is a sequence of bits that can be used with bitwise operations to change or flip bits in a byte or nibble. That may be a convoluted definition so let me give an example using Arduino-style code to try to clarify.

byte myByte B01001011;
myByte = myByte & B00010001;

This code yields myByte = B00000001. The & operator performs a bitwise and comparison between myByte and the bit mask given by B00010001. The result is also eight bits with ones where both myByte and the bit mask are ones and zeros elsewhere. Such bitwise comparisons are especially useful when operating on the ATmega328’s registers. They allow you to change bits you want without accidentally changing bits you don’t want to change for example, consider the following code which uses the bitwise or operator and a bitmask to ensure that just the third bit (bits are numbered from right to left starting with zero) of the imaginary register called MYREG is set to one.

MYREG = MYREG | B00001000;

The bitwise and operator can be used in a similar manner to ensure that a bit in a register is set to zero without accidentally changing any of the other bits. For example, the following code ensures that just the forth bit is set to zero without changing any of the other bits.

MYREG = MYREG & B11101111;

Bit masks can be especially useful when you want to perform sequential tasks according to the values of individual bits in a byte. For example, perhaps you want to send an serial output that encodes a byte using pulses of high (ones) or low (zeros) voltages. For example, let’s say you want to send the byte B00101010 using the voltage sequence low, low, high, low, high, low, high, low on Arduino digital pin 7. You could accomplish this using code like this.

const int outPin = 7;
cost byte myByte = B00101010;
void setup(void) {
   pinMode(outPin, OUTPUT);
void loop(void) {
   for (int ii = 0; ii < 7; ii++) {
      if  (myByte & (B10000000 >> ii)) {
      digitalWrite(outPin, HIGH);
   else {
      digitalWrite(outPin, LOW);

In the above code the >> operator is a right bitshift operator. It shifts each bit in the number B10000000 ii places to the right. The if statement will return true if any of the bits in the result of the bitwise and operation are one and will return false if all of the bits in the result are zero.

I hope you found this very brief introduction to bit masks helpful.

Leave a Reply

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