+ 2
PY : "|" pipe bitwise-operator - What's the purpose & any real time example?
Hi All, What exactly is the purpose of "|" pipe bit wise-operator and any real time examples please Regards, VJ
3 Respostas
+ 1
Bitwise Or, "|", is useful to ensure specific bits are set to 1 in an integer.
* It can toggle one or more bits from 0 to 1.
* If the specified bits are already 1 then they remain set to 1.
* It never toggles any bits from 1 to 0.
print(4 | 1) # outputs 5
This toggles the lowest bit of 4 to 1, so 4 becomes 5. In binary it looks like
100 | 001 = 101
print(5 | 4) # outputs 5
101 | 100 = 101, the 4 bit of 5 is already 1, so there is no change to the 5.
Here is a way to convert uppercase ASCII into lowercase by forcing bit 5 to be set to 1:
def ToLower(s):
res = ''
for c in s:
res += chr(ord(c) | 32) #bit5 is 32
return res
print(ToLower('AbC'), ToLower('aBc'))
# outputs abc abc
0
It is a bitwise OR of integers. I don't understand what you mean with real-time examples, but I hope this simple one works:
set([1,2]) | set([2,3]) it results in: set([1, 2, 3])
0
Thanks @Ricardo!!
Can you please advice the code to use above and is "bitwise OR" used to find unique in sets?