STM32 Tutorials: Bit Operations in C

In this tutorial we will learn how to make bitwise operations in C. It is important to know how to set, clear and toggle a bit in C. We will make use of them a lot 🙂

Bit Operators in C

In C bit operators are “&”, “|”, “~”, “^”, “>>”, “<<“.

AND Operator

“&” A.K.A. AND operation is a bit operator in C that evaluates to TRUE if all of its operands are true and FALSE otherwise.

OR Operator

“|” OR operator is a bit operator that returns a value of TRUE if either or both of its operands is TRUE.

NOT Operator

“~” NOT operator is a bit operator that returns TRUE if its operand is FALSE, and FALSE if its operand is TRUE.

XOR Operator

“^” XOR operator is that returns a value of TRUE only if just one of its operands is TRUE.

Left and Right Shift Operators

“<<” Left Shift operator is used to move values in given number. For example;

0x20 << 2 is 0x80

0x20 = 0b0010 0000

0x80 = 0b1000 0000

as you can see al the bits are shifted two times to the left. Its same in Right Shift but reverse the order.

Set a Bit

We are using OR operator to set a bit.

a = a | (1<<k) or a |= 1<<k

The above syntax means make kth bit of a TRUE, for example;

a = a | (1<<5)

We can simply use a = 0x20; but this will make all bits zero except 5th bit. If you don’t know what is a initially, do not use it, use bitwise operations instead.

Clear a Bit

We are using AND operator to reset a bit.

a = a & ~(1<<k) or a &= ~(1<<k)

The above syntax means; make kth bit of a FALSE, for example;

a = a & ~(1<<5)

Again we can simply use a = 0xDF; but this will make all bits one except 5th bit. If you don’t know what is a initially, do not use it, use bitwise operations instead.

Toggle a Bit

We are using XOR operator to toggle a bit. Toggling simply is changing state of the bit; if it’s TRUE make FALSE vice versa.

a = a ^ (1<<k) or a ^= 1<<k

The above syntax means; toggle kth bit of a, for example;

a = a ^ (1<<5)