Python - Operator Bit masking

Introduction

Bit-masking operations allow us to encode and extract multiple flags within a single integer.

The binary and hexadecimal number support in Python is to code and inspect numbers by bit-strings:

Demo

X = 0b0001          # Binary literals 
print( X << 2 )              # Shift left 
print( bin(X << 2) )         # Binary digits string 
print( bin(X | 0b010) )      # Bitwise OR: either 
print( bin(X & 0b1) )        # Bitwise AND: both 
# www.j  a va2  s  .c om
X = 0xFF            # Hex literals 
print( bin(X) )
print( X ^ 0b10101010 )      # Bitwise XOR: either but not both 
print( bin(X ^ 0b10101010) )
print( int('01010101', 2) )  # Digits=>number: string to int per base 
print( hex(85) )             # Number=>digits: Hex digit string

Result

Related Topic