Python - Operator Bitwise Operations

Introduction

Python supports operation on bits.

Here are some of Python's bitwise expression operators at work performing bitwise shift and Boolean operations on integers:

Demo

x = 1           # 1 decimal is 0001 in bits 
y = x << 2      # Shift left 2 bits: 0100 
print( y )
print( x | 2 )  # Bitwise OR (either bit=1): 0011 
print( x & 1 )  # Bitwise AND (both bits=1): 0001
# from  w  ww. j  a  va 2  s. co  m

Result

In the first expression, a binary 1 (in base 2, 0001) is shifted left two slots to create a binary 4 (0100).

Related Topics