+ 1

What is happening with this operator

print(1|0)

29th Mar 2017, 4:37 PM
Anirudh Gadari
Anirudh Gadari - avatar
3 Answers
+ 6
The pipe (I think?) sign is a bitwise OR binary operator. It tests if the bits in the binary equivalents of the numbers contain at least a 1. In simple terms: 1 = 0001 0 = 0000 -------------- 0001 Thus, 1 | 0 is 0001 which is outputted as 1 in decimal. From the above, the numbers are first converted into their binary forms. 1 is 0001 while 0 is 0000. Then an operation is carried out on each column. A single digit in their binary form is a bit. If 1 is found at least once in the column of bits, 1 is returned as an output. The only case 0 is returned is if both bits are 0. Below is the truth table for OR (|) operator: 1 0 = 1 1 1 = 1 0 1 = 1 0 0 = 0 Let's see 5 | 2. 5 = 0101 2 = 0010 ------------- 0111 Therefore, 5 | 2 = 0101 | 0010 = 0111 = 7. For more information on bitwise operators, ask Google. ^_^
29th Mar 2017, 4:56 PM
John
John - avatar
+ 5
For integer types (which is your example), it's the bitwise or operator. You can apply | also to sets, which gives the union of these two sets.
29th Mar 2017, 4:57 PM
Álvaro
0
ć“ˆïŒŸ
30th Mar 2017, 10:15 AM
Anyumo