-4

I have something that I haven't yet wrapped my head around yet; how does the | operand evaluate numbers?

#include<iostream>

int main()
{
    int x, y, z;
    x = 2;
    y = 4;

    z = x | y;
}

Why does z get assigned 6 in this case; how does this work?

halfer
  • 19,824
  • 17
  • 99
  • 186
Charles
  • 1,844
  • 1
  • 14
  • 21

3 Answers3

8

The operator | is called bitwise OR. and its truth table is

A  B   A|B ( operate on bits)
----------
0  0    0
0  1    1
1  0    1
1  1    1 

In your case x=2 and y=4. By assuming both x and y are 32 bit integer, while doing x | y just follow above table. It looks like

    MSB                                        LSB <-- little enidian
x = 0000 0000 | 0000 0000 | 0000 0000 | 0000 0010
                                                |
y = 0000 0000 | 0000 0000 | 0000 0000 | 0000 0100                                           
-------------------------------------------------
z = 0000 0000 | 0000 0000 | 0000 0000 | 0000 0110 => 6
--------------------------------------------------
Achal
  • 11,821
  • 2
  • 15
  • 37
2

| means bitwise OR. The OR is applied to each bit. (4 becomes 100, 2 becomes 10):

   4    0100
OR 2    0010
------------
== 6    0110
------------

Together the bitwise OR produces 110 which is 6.


Please note that this is not an addition and there is no carry of the bits like with the + operator.

So for example:

   6    0110
 + 2    0010
------------
== 8    1000
------------

but:

   6    0110
OR 2    0010
------------
== 6    0110
------------
wally
  • 10,717
  • 5
  • 39
  • 72
0

It is simple. '|' is called bitwise operator. It will return 1 if either of bits are 1. If both bits are 0, this operator will return 0.

x = 2 which is 0000 0010 (in bits representation) y = 4 which is 0000 0100

now if you apply '|', the result will become 0000 0110 which is 6.

kadina
  • 5,042
  • 4
  • 42
  • 83