Bit Manipulation – C Programming

In this article I would like to share with you how to deal with bit manipulation of variable (mostly registers of peripherals). I would like to underline that this topic is very important in programming microcontrollers. I would like also to point out that this article will only be about manipulation in C programming because there are different ways in each programming language. Let’s explain this topic in a very accessible and simple way!

Setting a bit

uint8_t variable;
variable = variable | (1<<position_of_bit); 

You can also do it in the shorter way:

variable |= (1<<position_of_bit);

Resetting a bit

uint8_t variable;
variable = variable & ~(1<<position_of_bit);

The shorter version will look like this:

variable &= ~(1<<position_of_bit);

Toggling a bit

uint8_t variable;
variable = variable ^ (1<<position_of_bit);

Shorter version:

variable ^= (1<<position_of_bit);

Using macros also makes this task easier:

#define SET_BIT(x, pos) (x |= (1U << pos))
#define RESET_BIT(x, pos) (x &= (~(1U<< pos)))
#define TOGGLE_BIT(x, pos) x ^= (1U<< pos)
#define CHECK_BIT(x, pos) (x & (1UL << pos))

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s