This program is to set and clear a particular bit in a given number.
The logic used will be:
- To set a particular bit: ORing the bit with 1
- To clear the particular bit: ANDing the bit with 0.
- All the numbers are represented in 32 bits.
#include <stdio.h>
#define MAX_SIZE sizeof(int) *8
int display_binary (unsigned int num)
{
int i;
for(i = MAX_SIZE-1; i>=0; i--)
{
if((num >> i)&1)
printf("1");
else
printf("0");
}
}
int main()
{
unsigned int num, pos;
printf("\n Enter the number: ");
scanf("%d", &num);
printf("\n Enter the position: ");
scanf("%d", &pos);
/* To set the bit */
printf("\n The org number is: %d :", num);
display_binary(num);
num = num | (1UL << pos);
printf("\n The new number after setting %d bit is: %u binary:", pos, num);
display_binary(num);
/* To clear the bit */
num = num & ~(1UL << pos);
printf("\n The new number after clearing bit %d is: %u binary:", pos, num);
display_binary(num);
return 0;
}
Output:
Enter the number: 12
Enter the position: 4
The org number is: 12 :00000000000000000000000000001100
The new number after setting 4 bit is: 28 binary:00000000000000000000000000011100
The new number after clearing bit 4 is: 12 binary:00000000000000000000000000001100
Example:
For simplicity it is shown in 8 bits.
To set:
num = 8 = 0000 1000
mask = 1 << 2 = 0000 0100
num | mask = 0000 1100 = 12
To clear:
num = 8 = 0000 1000
mask = 1 << 2 = 0000 0100
~mask = 1111 1011
num & ~maks = 0000 1000 = 8
Categories: C Language
Leave a Reply