How to Toggle a Particular Bit in a number: A Step-by-Step Guide

In this blog post, I will teach you how to write C/C++ program to toggle a particular bit in a number. After reading this detail guide post I believe you able to write an efficient program to toggle bit in a number.

Consider the below examples,

Example-1:

Input : n = 5


Here's a simple ASCII representation of 5 (an 8-bit integer):
  7   6   5   4   3   2   1   0    (Bit position)
+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 0 | 1 | 0 | 1 |  (Example bit values)
+---+---+---+---+---+---+---+---+
                  ^
                  |
                 Want to toggle this Bit (3rd bit)



(After toggling bit) 
Output: 13

  7   6   5   4   3   2   1   0    (Bit position)
+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 |  (Example bit values)
+---+---+---+---+---+---+---+---+
                  ^
                  |
                 You can see bit has been toggled.

 

Example-2:

Input : n = 13

Here's a simple ASCII representation of 13 (an 8-bit integer):

  7   6   5   4   3   2   1   0    (Bit position)
+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 1 | 1 | 0 | 1 |  (Example bit values)
+---+---+---+---+---+---+---+---+
                      ^
                      |
                      Want to toggle this Bit (2nd bit)



(After toggling bit) 

Output: 9

  7   6   5   4   3   2   1   0    (Bit position)
+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 1 | 0 | 0 | 1 |  (Example bit values)
+---+---+---+---+---+---+---+---+
                  ^
                  |
                 You can see bit has been toggled.

 

 

Let’s see the problem statements for this question.

Problem Statement: Given a number ‘n’, the task is to clear the d-th bit of this number n. If dth bit is 0, then set it to 1 and if it is 1 then set it to 0.  Note that d = 0 means the rightmost bit of ‘n’.

Disclaimer: Try to solve the problem yourself first otherwise it would be not worth solving this problem.

 

1. Using Bitwise Ex-OR (^) with a Bit Mask:

With the help of Bitwise EX-OR (^) and a Mask you can easily toggle the bits of a given number. In this approach we use a bit mask to toggle the bit at the specified position.

Using the expression (1 << d), you can create a mask. This mask has only a set bit which you want to check.

After creating the mask, you need to perform the bitwise EX_OR between given number ‘n’ and the mask. Now dth bit of given number ‘n’ is toggle.

Let’s take an example to understand the above steps, suppose n =5.

Now if you want to toggle its 3rd bit (bit-position start from the 0), so here mask would be (1<<3).

Mask: (1 << 3)


  7   6   5   4   3   2   1   0    (Bit position)
+---+---+---+---+---+---+---+---+
| 0 | 0 | 0 | 0 | 1 | 0 | 0 | 0 |  (Example bit values)
+---+---+---+---+---+---+---+---+

 

Now EX-Oring this mask with original number ‘n’.

Original number n: 5

                   00000101 (5 in binary)
                    ^
Mask:              00001000


Result: =          00001101

 

As you know XOR of unset (0) and set bit (1) results in a set bit and XOR of a set and set bit results in an unset bit. Hence performing bitwise XOR of any bit with a set bit results in toggle of that bit, i.e.

That means,

0 ^ 0 = 0
1 ^ 0 = 1
0 ^ 1 = 1
1 ^ 1 = 0

 

Now let see few programming examples for the better understanding.

 

C program to toggle a particular bit in a number:

/*
C program to toggle a
particular bit in a number
*/


#include <stdio.h>
//If d valid, then returns a number
// that has all bits same as n
// except its d'th bit which is toggle.
unsigned int toggleDthBits(unsigned int n, int d)
{
    unsigned int tmpN = n ;
    //d must be greater than 0
    if(d > 0)
    {
        tmpN = (n ^ (1 << d));
    }
    else
    {
        printf("Enter valid value of position\n");
    }
    return tmpN;
}

int main()
{
    int n = 5;
    int d = 3;

    const unsigned int v = toggleDthBits(n, d);

    printf("v = %u", v);

    return 0;
}

 

 

C++ program to toggle a particular bit in a number:

/*
C++ program to toggle a
particular bit in a number
*/

#include <iostream>


//If d valid, then returns a number
// that has all bits same as n
// except its d'th bit which is toggle.
unsigned int toggleDthBits(unsigned int n, int d)
{
    unsigned int tmpN = n ;
    //d must be greater than 0
    if(d > 0)
    {
        //Create MASK
        const unsigned int MASK = (1 << d);

        tmpN = (n ^ MASK);
    }
    else
    {
        std::cout<<"Enter valid value of position"<<std::endl;
    }
    return tmpN;
}


int main()
{
    int n = 5;
    int d = 3;

    const unsigned int v = toggleDthBits(n, d);

    std::cout<<"v = "<< v<<std::endl;

    return 0;
}

 

Recommended Post

Leave a Reply

Your email address will not be published. Required fields are marked *