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
    • say mask = ~mask
  • 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;
  mask = ~mask;
  num = num & mask;
  printf("\n mask %u", mask);
 
  
  printf("\n Mask is:");
  display_binary(mask);

  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
Mask is:11111111111111111111111111111100
The result is: 4  binary:00000000000000000000000000000100


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: