Bitwise AND
The bitwise AND is True only if both bits are set. The following example shows the result of a bitwise AND on the numbers 23 and 12.
10111 (23)
01100 (12) AND
____________________
00100 (result = 4) |
You can use a mask value to check if certain bits have been set. If we wanted to check whether bits 1 and 3 were set, we could mask the number with 10 (the value if bits 1 and 3) and test the result against the mask.
#include <stdio.h>
int main()
{
int num, mask = 10;
printf("Enter a number: ");
scanf("%d", &num);
if ((num & mask) == mask)
puts("Bits 1 and 3 are set");
else
puts("Bits 1 and 3 are not set");
return 0;
}
Bitwise OR
The bitwise OR is true if either bits are set. The following shows the result of a bitwise OR on the numbers 23 and 12.
10111 (23)
01100 (12) OR
______________________
11111 (result = 31) |
You can use a mask to ensure a bit or bits have been set. The following example ensures bit 2 is set.
#include <stdio.h>
int main()
{
int num, mask = 4;
printf("Enter a number: ");
scanf("%d", &num);
num |= mask;
printf("After ensuring bit 2 is set: %d\n", num);
return 0;
}
|