To toggle a particular bit

This program is for toggling a particular bit that is if the bit is set clear and set it if it is clear.

We will be using a Xor operator for doing so that is Xor that particular bit with 1. We will be using a masking technique that is have a new number where only the asked bit is set.( 1<< pos)

#include <stdio.h>
#define MAX_BIT (sizeof(int) * 8)

int display_binary(unsigned int num)
{
   int i;
   for(i = MAX_BIT-1; i>=0; i--)
   {
       if((num >> i)&1)
         printf("1");
       else
         printf("0");
   }
}


int main()
{
  unsigned int num, pos;
  printf("\n Enter the number: ");
  scanf("%d", &num);
  printf("\n Enter the position to be toggled: ");
  scanf("%d", &pos);

  unsigned int toggle_num = num ^ (1UL << pos -1);
  printf("\n The value before toggling is: %u decimal:", num);
  display_binary(num);
  printf("\n The value before toggling is: %u decimal:", toggle_num);
  display_binary(toggle_num);
 
  return 0;
}

Output:

Enter the number: 255

Enter the position to be toggled: 3

The value before toggling is: 255 decimal:00000000000000000000000011111111
The value before toggling is: 251 decimal:00000000000000000000000011111011


Categories: C Language

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

%d bloggers like this: