Need help understanding | operator | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Need help understanding | operator

I am having trouble understanding how we get the answer 30 here. I understand the | symbol is interpreted as a bitwise OR, but that doesn’t in any way help me understand why the answer in 30 lol. Any help would be appreciated! Input: def f(m, n): return m|n print(f(10, 20)) output: 30

22nd Apr 2018, 8:29 PM
stephanie
stephanie - avatar
6 Answers
+ 1
The | operator corresponds to the logical OR expression. This means that your arguments will be treated as binary numbers, and starting with the lowest value digits (rightmost) for each one number, if they are both 0 the result's digit at this position will also be 0, otherwise it will be 1. For example 10(decimal) = 01010(binary) and 20(decimal) = 10100(binary). So, 01010 OR 10100 = 11110(binary) = 30(decimal).
22nd Apr 2018, 8:46 PM
Tanasis
Tanasis - avatar
22nd Apr 2018, 8:40 PM
Ariela
Ariela - avatar
+ 2
In this case you have to write the binary representation of the two numbers,then they will be checked with the bitwise or operator 01010 for 10 10100 for 20 01010 | 10100 ===> 11110 convert it to decimal gives us 30 Don't forget that 0|1 == 1 and 1|1 == 1
22nd Apr 2018, 8:47 PM
HBhZ_C
HBhZ_C - avatar
+ 1
thank you so much!
22nd Apr 2018, 8:41 PM
stephanie
stephanie - avatar
+ 1
In binary, 10 is 1010, 20 is 10100. 10|20 = 11110 which is 30. This case gives you by chance the sum, but it is not really the case 😁
22nd Apr 2018, 8:47 PM
jerome
+ 1
wow thank all you guys. This is super helpful
22nd Apr 2018, 9:10 PM
stephanie
stephanie - avatar