Java num1 | num2 , what is this operator? [duplicate]
It's a bitwise OR operation. It's modifying things at a binary level.
011 3
in binary: | 100 in decimal: | 4
___ ___
111 7
Open Windows calc using scientific mode. You can flip between decimal and binary (and hex) and perform bitwise operations including or, and, xor, etc.
To do a bitwise or in your head or on paper, compare each digit of the same ordinal. If either number is a 1, the result at that ordinal will be 1.
The operator |
does a "bitwise OR". The output of bitwise OR on two bits is 1 if either bit is 1 or 0 if both bits are 0. Bitwise OR on two numbers just does a bitwise OR on each bit individually.
Heres how 3|4
works:
3: 00000011
4: 00000100
--------------
3|4: 00000111 = 7
It's doing a bitwise OR
operation, and 3 OR
4 is 7.
See here: http://en.wikipedia.org/wiki/Bitwise_OR#OR
Binary representation:
3 = 00000011
4 = 00000100
| is bitwise OR operator
when you OR two numbers, you take the binary representation and the OR result is 1 IFF for that column at least one column is set true (1)
So
00000011
00000100
--------
00000111
then, columns tell you the value at that position:
128, 64, 32, 16, 8, 4, 2, 1
so
128, 64, 32, 16, 8, 4, 2, 1
0 , 0, 0, 0, 0, 1, 1, 1
any column with a 1 means you add that column's value:
4 + 2 + 1 = 7
| is the "bitwise or" operator. in a|b, if nth bit of a and/or b is 1, the nth bit of the result will be 1. 3 is 11 in binary. 4 is 100 in binary.
0 1 1
or or or
1 0 0
= = =
1 1 1
And 111 happens to be the binary representation of 7.