What is the value of 5 | 3 in C?

1.9k Views Asked by At

According to boolean algebra, 5 is equivalent to 101 in binary. And 3 is equivalent to 011. So if we calculate 101 | 011 then it should be 1000 which is equivalent to 2^3 = 8 but in vs code the compiler gives 7, is there any error in my solution?

2

There are 2 best solutions below

0
Vlad from Moscow On

According to the C Standard (6.5.12 Bitwise inclusive OR operator)

4 The result of the | operator is the bitwise inclusive OR of the operands (that is, each bit in the result is set if and only if at least one of the corresponding bits in the converted operands is set).

So you have

 101
|
 011
====
 111
0
Jyothi On

You have to do the or operation for individual bits, as 1|0=1,1|1=1,0|1=1,0|0=0.

for 5,the value in bits=1 0 1
for 3,the value in bits=0 1 1
                        ------
                        1 1 1,which is 7.