& in print function -- python3

205 views Asked by At

print(2 & 3)

I came across a problem statement in one of my technical assessments, I can't understand the usecase of this '&' operator. Can anyone help me, with how this & operator work in python3

1

There are 1 answers

0
ti7 On

& is a bitwise operator, so this is simply where the binary bits line up between 2 and 3
https://wiki.python.org/moin/BitwiseOperators

>>> bin(2)
'0b10'
>>> bin(3)
'0b11'
>>> int("0b10", base=2)  # binary string -> int (base10)
2

Here's an example with some bigger numbers

>>> bin(12)
'0b1100'
>>> bin(10)
'0b1010'
>>> 12&10
8
>>> bin(8)
'0b1000'
>>> bin(~8)  # NOTE 8 is signed
'-0b1001'
>>> 8&-8
8