Clear/Set a specific bit of a number in Arduino

ArduinoArduino BoardsArduino IDEArduino Programming Language

When you delve into advanced firmware, you deal with a lot of registers, whose specific bits need to be set or cleared depending on your use case. Arduino has inbuild functions to do that.


bitSet(x, index)


bitClear(x, index)

Where x is the number whose bit has to be set/ cleared and index is the position of the bit (0 for least significant or right-most bit). This function makes changes in the number x in place, and also returns the updated value of x.

Note that setting a bit means setting its value to 1, and clearing it means setting its value to 0.


The following example illustrates the use of these functions −

void setup() {
   // put your setup code here, to run once:
   int x = 6;


void loop() {
   // put your main code here, to run repeatedly:


The Serial Monitor output is shown below −

As you can see, we start off with the number 6 (0b0110).

We then set its 0th bit, yielding (0b0111), which corresponds to 7.

Then, we clear its 2nd bit, yielding (0b0011), which corresponds to 3.

We then clear its 3rd bit, which was already 0. Thus, we again get (0b0011), which corresponds to 3.

The Serial Monitor output shows these numbers in the exact sequence we just described.

Published on 31-May-2021 14:23:47