C Program to clear the ith Bit of a Binary Number i.e. Changes the bit from 1 to 0, otherwise remains same - Bit Manipulation


 
// Program by Akash Tripathi (@proakash256) 
 
// Example : 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 = 10i >= 0i = 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,
    // negate it and then AND(&) it with n

    int mask = ~(1 << i);
    n = n & mask;

    printf("\nNew Number is %d\n" , n);
    printf("Binary Representation of %d is : ");
    binary(n);
    return 0;
}

Comments