+ 5

Help me! I don't understand this operator in Python

I don't know how this works: 2|4=6 3|6=7 4|7=7 1|3=3 somebody can tell me what's the logic here? (And it's name if you know it)

18th Feb 2017, 4:47 PM
Ivan Truenow
Ivan Truenow - avatar
5 odpowiedzi
+ 14
here is an answer i posted a while ago. what you are looking for is the Bitwise OR operator Logical operators: OR || takes two conditionals, return true if EITHER is true AND && takes two conditionals, return true if BOTH are true Bitwise operators: work on the bit level, compare each bit that build a value and act accordingly i will use small values which can be represented with 4 bits only. we will find x on each example OR | example: 5 | 3 = x 5 = 0101 3 = 0011 x = 0111 = 7 (bits in x are set by the bits of 5,3) AND & example: 5 & 3 = x 5 = 0101 3 = 0011 x = 0001 = 1
18th Feb 2017, 4:57 PM
Burey
Burey - avatar
+ 10
I don't know much about python but I found this online: | Binary OR It copies a bit if it exists in either operand. Example: (a | b) = 61 (means 0011 1101) You can find this information and more here: https://www.tutorialspoint.com/python/python_basic_operators.htm. Hope it helps😉
18th Feb 2017, 4:57 PM
C.E.
C.E. - avatar
+ 6
And if you want to know why in the world you'd EVER use this... Status codes are often kept as a 'list of bits' for efficiency, speed, global sharing or convenience (and these bits are often called flags). Imagine a 3D printer: STATUS_NOZZLE_HOT=1 STATUS_NOZZLE_OLD=2 STATUS_NOZZLE_JAMMED=4 STATUS_NOZZLE_STARVED=8 STATUS_MEDIA_READY=16 ...32, 64, 128 Now 8 panel lights (or LCD icons) can readily be set/extinguished by a single status byte, or you can combine tests: SVC_FLAGS = (...old | jammed | starved) # 2|4|8 = 2+4+8 = 14 # One or more flags 'set'? if STATUS & SVC_FLAGS > 0: print("Nozzle needs service.")
20th Feb 2017, 3:00 PM
Kirk Schafer
Kirk Schafer - avatar
+ 6
@Ivan - Added a sample test after you saw it. Heads up.
20th Feb 2017, 3:21 PM
Kirk Schafer
Kirk Schafer - avatar
+ 6
Thank you! Now I understand
20th Feb 2017, 3:23 PM
Ivan Truenow
Ivan Truenow - avatar