
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))
[…] recently posted a content which was related to bit manipulation in C programming and now I decided to show you how to do same […]
LikeLike