-4

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);
}
Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
BlackCat
  • 1,932
  • 3
  • 19
  • 47
  • 10
    why would it print 27 – Tyker Jun 08 '18 at 14:47
  • `20` is `00010100`, `7` is `00000111`. `|` is ["bitwise or"](https://en.wikipedia.org/wiki/Bitwise_operation#OR) and it means a bit in the result is `1` if the corresponding bit is `1` for at least one of the operands. `20 | 7` is obviously `00010111` which is `16+7`. – axiac Jun 08 '18 at 14:49
  • 1
    You can use your windows calculator in "programmer" mode. This will save you from similar questions. – Eugene Sh. Jun 08 '18 at 14:50
  • 4
    Why a programmer can't tell between Christmas from Halloween? Because Dec 25 = Oct 31. – Eugene Sh. Jun 08 '18 at 14:52
  • Try `printf("%o",a|b);` – Eugene Sh. Jun 08 '18 at 15:02

2 Answers2

6

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.

paxdiablo
  • 854,327
  • 234
  • 1,573
  • 1,953
3

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.

gsamaras
  • 71,951
  • 46
  • 188
  • 305