Clear till ith bit from MSB

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

Example:

number = 224 : 1110 0001
ith bit = 3
Result= 1 : 0000 0001

Logic:

  • For clearing say till 2nd bit, we need AND till the 3 bit from MSB with 0 and rest with 1
  • That is ANDing should be done with 0001 1111
  • To get that number:
    • If we do mask = (1 << MAX_BIT – bit ) -1) = (1 << 8 -3 ) -1
  • 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 << MAX_BIT - bit) -1;
  num = num & 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 : 2147483648

Enter the bit position :1

The given number is 2147483648:  binary: 10000000000000000000000000000000
Mask is:01111111111111111111111111111111
The result is: 0  binary:00000000000000000000000000000000


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: