Setting and resetting bits in a number

In microcontroller code (and other places that use “flags”), you often need to set a specific bit to 0 or 1 in a register.

The bit number is given by an index. REGISTER here is the register or variable being modified.

This example is in C, though the syntax is similar in many programming languages.

	// Setting a specific bit to 1
	REGISTER |= (1 << index);

	// Setting a specific bit to 0
	REGISTER &= ~(1 << index);


|= is like +=. The latter adds the right operand to the value of the variable and then assigns the resulting value to the variable on the left. In this case we’re using a bitwise OR instead.

(1 << index) takes the value 1 and bit-shifts it index positions to the left, padding with 0s on the right. With an index of 3, this produces 1000 (in binary).

A bitwise OR means that all bits where the our constructed value have a 0 will be kept as they were in the variable. Where the right operand’s bit is 1, the variable’s value will be set to 1 regardless of what was in there.


&= operates like the |= as describe before, but performs a bitwise AND operation.

the ~ before (1 << index) is a bitwise NOT, meaning it flips all 0s to 1s and vice versa.

In this case, re-using our index of 3, we got 1000 -> NOT -> 0111. Essentially all bits in the number not at position 3 will be 1 instead of 0.

A bitwise AND then means that we keep all values as they were in the variable, where the matching bit in the right operand is 1. Where it is 0, it will be set to 0.

Further reading: Bitwise operation on Wikipedia