Home / Learn / Code for makers

Bits, bytes and bitwise operations for makers

An 8-bit register with bit 3 being set by OR-ing it with a mask
Beginner

Sooner or later every electronics project needs bit manipulation. A sensor sends a temperature as two separate bytes. A display chip wants one bit set in a control register. A datasheet says "bits 6 to 4 select the mode". The tools for this are the bitwise operators, and once you've seen the handful of patterns below, you'll recognise them in every driver you read.

Bits and bytes in a nutshell

A bit is a single 0 or 1. A byte is 8 bits, numbered 0 to 7 from the right, where bit 0 is the least significant and is worth 1, and bit 7 is worth 128. Hex is a compact way to write bytes: each hex digit is exactly four bits, so 0xA5 is 1010 0101. Our base converter translates between them.

The six operators

OperatorNameWhat it doesExample
&AND1 only where both bits are 15 & 3 = 1
|OR1 where either bit is 15 | 3 = 7
^XOR1 where the bits differ5 ^ 3 = 6
~NOTFlips every bit~5 = −6 in Python
<<Shift leftMoves bits left, filling with 0s5 << 1 = 10
>>Shift rightMoves bits right, dropping the lowest5 >> 1 = 2

5 is 101 and 3 is 011, so AND gives 001, OR gives 111 and XOR gives 110. Python integers have no fixed size, so ~5 shows as −6, the two's complement result. That's why masks such as & 0xFF are used to keep results to 8 bits.

Setting, clearing, toggling and testing a bit

1 << n makes a number with only bit n set. That's called a mask, and four patterns cover nearly everything:

STATUS = 0b0000_0000

STATUS |= (1 << 3)          # set bit 3
print(bin(STATUS))           # 0b1000
STATUS |= (1 << 0)          # set bit 0
print(f"{STATUS:08b}")       # 00001001
STATUS &= ~(1 << 3)         # clear bit 3
print(f"{STATUS:08b}")       # 00000001
STATUS ^= (1 << 7)          # toggle bit 7
print(f"{STATUS:08b}")       # 10000001
print(bool(STATUS & (1 << 7)))   # test bit 7: True
  • Set with OR: OR with 1 forces a bit to 1 and leaves the others alone.
  • Clear with AND NOT: the inverted mask has a 0 only at the bit you want to clear.
  • Toggle with XOR.
  • Test with AND: the result is non-zero only if the bit is set.

The f"{x:08b}" format shows a value as 8 binary digits with leading zeros. Underscores in number literals, like 0b0000_0000, are just for readability.

Reading and writing a field inside a register

Datasheets often pack several settings into one byte. Suppose bits 6 to 4 of a register hold a 3-bit "mode". To read it, shift the field down to bit 0, then mask off the three bits:

reg = 0b1011_0110
mode = (reg >> 4) & 0b111
print(mode)                  # 3

To change the mode without disturbing the other bits, clear the field, then OR in the new value shifted into place. This read-modify-write pattern is the standard way to update a register over I²C or SPI:

reg = (reg & ~(0b111 << 4)) | (0b010 << 4)
print(f"{reg:08b}")          # 10100110

Joining and splitting bytes

Sensors with 16-bit readings usually send a high byte and a low byte. Shift the high byte up by 8 and OR them together:

high, low = 0x01, 0x90
raw = (high << 8) | low
print(raw)                   # 400
print(raw >> 8, raw & 0xFF)  # 1 144

Check the datasheet for the byte order. Some chips send the low byte first. If the reading is signed, convert it with two's complement afterwards: if bit 15 is set, subtract 65,536. Our base converter explains why.

The same code in C and Arduino

The operators are identical in C, C++ and Arduino, and the same patterns appear in every driver: reg |= (1 << 3);, reg &= ~(1 << 3); and uint16_t raw = (high << 8) | low;. Two differences matter. C integers have fixed sizes, so use types like uint8_t and uint16_t to be clear about widths. And right-shifting a negative signed number in C behaves differently between compilers, so do bit work on unsigned types. Arduino also has helpers such as bitSet(), bitClear() and bitRead().

Sources

The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.