To toggle a number

This program is for toggling the complete number that is the set bit is to be cleared and clear bit has to be set.

The logic would be using XORing each bit by 1.

Example:

num = 1001 0011
mask = 1111 1111
———————————-
num ^mask = 0110 1100

#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, org_num, toggled_num;
  printf("\n Enter the number: ");
  scanf("%u", &num);
  org_num =  num;
  
  int i = 0;
  for (i; i < MAX_BIT; i++)
    num = num ^ (1UL << i);
 
 printf("\n The value before toggling is: %u decimal: ", org_num);
 display_binary(org_num);
 printf("\n The value before toggling is: %u decimal: ", num);
 display_binary(num);
 
 return 0;
}

Output:

Enter the number: 255

The value before toggling is: 255 decimal: 00000000000000000000000011111111
The value before toggling is: 4294967040 decimal: 11111111111111111111111100000000


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: