Bitwise Operations
In Python, bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into binary and then operations are performed on bit by bit, hence the name bitwise operators. The standard bitwise operations are demonstrated below.
Note: For more information, refer to Python Bitwise Operators
Example:
Python3
# Code to demonstrate bitwise operations # Some bytes to play with byte1 = int ( '11110000' , 2 ) # 240 byte2 = int ( '00001111' , 2 ) # 15 byte3 = int ( '01010101' , 2 ) # 85 # Ones Complement (Flip the bits) print (~byte1) # AND print (byte1 & byte2) # OR print (byte1 | byte2) # XOR print (byte1 ^ byte3) # Shifting right will lose the # right-most bit print (byte2 >> 3 ) # Shifting left will add a 0 bit # on the right side print (byte2 << 1 ) # See if a single bit is set bit_mask = int ( '00000001' , 2 ) # Bit 1 # Is bit set in byte1? print (bit_mask & byte1) # Is bit set in byte2? print (bit_mask & byte2) |
Output:
-241 0 255 165 1 30 0 1
Working with Binary Data in Python
Alright, lets get this out of the way! The basics are pretty standard:
- There are 8 bits in a byte
- Bits either consist of a 0 or a 1
- A byte can be interpreted in different ways, like binary octal or hexadecimal
Note: These are not character encodings, those come later. This is just a way to look at a set of 1’s and 0’s and see it in three different ways(or number systems).
Examples:
Input : 10011011 Output : 1001 1011 ---- 9B (in hex) 1001 1011 ---- 155 (in decimal) 1001 1011 ---- 233 (in octal)
This clearly shows a string of bits can be interpreted differently in different ways. We often use the hex representation of a byte instead of the binary one because it is shorter to write, this is just a representation and not an interpretation.
Contact Us