# Clear till ith bit from LSB

This program is to clear all the bit starting from LSB till the ith bit

Example:

number = 7 : 0000 0111
ith bit = 2
Result= 4 : 0000 0100

Logic:

• For clearing say till 2nd bit, we need AND till the 2 bit from LSB with 0 and rest with 1
• That is ANDing should be done with 1111 1100
• To get that number:
• If we do mask = (1 << 2) -1 = 4 -1 = 3 i.e 0000 0011
• If we see its just invert of what we need, so invert it
• and then num = num & mask
``````#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, bit;
printf("\n Enter the first number : ");
scanf("%d",&num);

printf("\n Enter the bit position :");
scanf("%d",&bit);
printf("\n The given number is %u:  binary: ", num);
display_binary(num);

int mask = (1UL << bit) -1;

printf("\n The result is: %u  binary:", num);
display_binary(num);

return 0;
}``````

Output:

``````Enter the first number : 7

Enter the bit position :2

The given number is 7:  binary: 00000000000000000000000000000111