C Program to Toggle the ith Bit of a Binary Number i.e. Changes the bit from 0 to 1 or 1 to 0 - Bit Manipulation
// Program by Akash Tripathi (@proakash256)
// Example 1: Let n = 100110101 and i = 4
// Bit at 4th position is 0,
// So it is changed to 1
// New Number = 100111101
// Example 1: Let n = 100110101 and i = 5
// Bit at 5th position is 1,
// So it is changed to 0
// New Number = 100100101
// In this Program position starts from 1
// but in binary representation it starts from 0
#include <stdio.h>
void binary(int n)
{
// Prints the Binary Representation
// of a Decimal Number upto 11 bits.
for(int i = 10; i >= 0; i = i - 1)
{
printf("%d" , ((n >> i) & 1));
}
printf("\n");
return;
}
int main()
{
int n , i;
printf("Enter the Number : ");
scanf("%d", &n);
printf("Binary Representation of %d is : ", n);
binary(n);
printf("Enter the Position : ");
scanf("%d", &i);
i = i - 1;
// In this Method, we
// left shift(<<) 1 i times
// and then XOR(^) it with n
int mask = 1 << i;
n = n ^ mask;
printf("\nNew Number is %d\n" , n);
printf("Binary Representation of %d is : ", n);
binary(n);
return 0;
}
Comments
Post a Comment