C Program to Set the Most Significant Bit (MSB) and Least Significant Bit (LSB) till ith bit - Bit Manipulation
// Program by Akash Tripathi (@proakash256)
// Example : a = 59 which is 00000111011
// and i = 4
// So LSBs till 4th position are cleared
// New Number = 00000111111
// And
// MSBs till 4th position are cleared
// New Number = 11111111011
// 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 , temp;
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;
temp = n;
// For Setting LSBs
// In this Method, we
// left shift(<<) 1 (i + 1) times,
// subtract 1 from it and then
// negate it and then AND(&) it with n
int mask = ((1 << (i + 1)) - 1);
temp = temp | mask;
printf("\nNew Number is %d\n" , temp);
printf("Binary Representation of %d is : ");
binary(temp);
temp = n;
// For Setting MSBs
// In this Method, we
// left shift(<<) 1 (i + 1) times,
// subtract 1 from it and then
// AND(&) it with n
mask = (~((1 << (i + 1)) - 1));
temp = temp | mask;
printf("\nNew Number is %d\n" , temp);
printf("Binary Representation of %d is : ");
binary(temp);
return 0;
}
Comments
Post a Comment