Can anyone explain how this code snippet gives output as 23 instead of 27. I may have less understanding in bitwise operations.
#include <stdio.h>
int main()
{
int a = 20, b = 7;
printf("%d%",a|b);
}
Can anyone explain how this code snippet gives output as 23 instead of 27. I may have less understanding in bitwise operations.
#include <stdio.h>
int main()
{
int a = 20, b = 7;
printf("%d%",a|b);
}
You need to first understand how or
works at a bit level (see here for more detail on the various bitwise operators):
0 | 0 = 0
0 | 1 = 1
1 | 0 = 1
1 | 1 = 1
Note that last line carefully, 1 | 1
is not the same as 1 + 1
.
So, since the result of or
on multi-bit values just involves doing it on each of the corresponding bits in those values, the expression a | b
will only be equal to a + b
if the two values share no one-bits in common.
For your values, they do share a one-bit:
+-shared one-bit--+
| |
V V
20 = 16 + 4 = 0001 0100
7 = 4 + 2 + 1 = 0000 0111
---- ----
20 | 7 = 0001 0111 = 16 + 4 + 2 + 1 = 23
That explains the value that you're getting and why it's not the same as 20 + 7
.
Because in binary 20 is 10100 and 7 is 00111.
So you have:
10100
00111 |
-----
10111
which is the binary representation for 23, not 27.
PS: |
is the bitwise or operator, so if at least an operand is 1, it gives 1, else 0.