#printing decimal to binary
print(bin(120).replace('0b','')) # 1111000
# binary to decimal
print(int('1111000',2)) # 120
Returns 1 when both operands are 1, otherwise returns 0.
print(3 & 4) # 0
print(bin(3).replace('0b','')) # 11
print(bin(4).replace('0b','')) # 100
print(12 & 15) # 12
print(bin(12).replace('0b','')) # 1100
print(bin(15).replace('0b','')) # 1111
Returns 0 if both operands 0, otherwise returns 1.
print(12 | 15) # 15
print(bin(12).replace('0b','')) # 1100
print(bin(15).replace('0b','')) # 1111
print(34 | 12) # 46
print(bin(34).replace('0b','')) # 100010
print(bin(12).replace('0b','')) # 1100
print(int('101110',2)) # 46
Returns 1 of both operands are different, otherwise 0.
print(12 ^ 15) # 3
print(bin(12).replace('0b','')) # 1100
print(bin(15).replace('0b','')) # 1111
print(34 ^ 12) # 46
print(bin(34).replace('0b','')) # 100010
print(bin(12).replace('0b','')) # 1100
print(int('101110',2)) # 46
Flips the bits until one 0 is reached (from right side ) ~x = -x-1
Examples
print(~15) # -16
print(~4) # -5
print(~-22) # 21
print(~99) # -100
This shifts left the binary number by given ( input ) places. The place vacated at left is filled by zeros.
print(14<<2) # 56
print(bin(14).replace('0b','')) #1110
This shifts right the binary number by given ( input ) places.
print(14>>2) # 3
print(bin(14).replace('0b','')) #1110
print(90>>3) # 11
print(bin(90).replace('0b','')) #1011010
print(int('1011',2)) #11
print(14<<1) # 28
print(14>>1) # 7
print(100 <<1) # 200
print(100 >>1) # 50
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.