In information theory, the Hamming distance between two equally long strings is the number of positions at which the corresponding characters are different. In other words, it’s the minimum number of substitutions required to transform one string into the other. If the strings are binary, the Hamming distance can be calculated very simply using a bitwise XOR operation.
Here, we will introduce how to use binary representation and perform bitwise operations in Python 3.
Binary Representation in Python
In Python, binary numbers can be represented by strings prefixed with "0b"
or "-0b"
. We can also use the bin()
function to convert a numerical value into its binary string form.
print(0b1101)
#13
print(0b11111110)
#254
bin(5)
#'0b101'
Binary Bitwise Operations
Python provides the following bitwise operations:
>>
: Right shift<<
: Left shift|
: Bitwise OR&
: Bitwise AND^
: Bitwise XOR~
: Bitwise NOT
Let’s look at them in detail below.
Left Shift
A left shift is equivalent to multiplying the number by 2 raised to the power of the shift amount.
0b11
is the machine code for 3. After shifting, it becomes 0b1100
, which is 12. So, 3 * 2**2 == 12
. Similarly, other numbers in the image above can be converted to their decimal values using this method.
Right Shift
0b101001 >> 2
#10
0b1011 >> 4
#0
0b1011 >> 3
#1
0b101101010 >> 3
#45
-16 >> 2
#-4
8 >> 1
#4
A right shift is equivalent to dividing by 2 raised to the power of N, where N is the number of bits shifted to the right. Note that in Python 3, division results automatically become float values, which is a difference from Python 2.
>>> 4/3
1.3333333333333333
>>> 4//3
1
OR
>>> 0b1101 | 0b1010
15
>>> 0b100 | 0b100
4
In a bitwise OR operation, if either of the corresponding bits is 1, the result for that position is 1. The final binary result is then converted to decimal.
AND
>>> 0b110 & 0b100
4
>>> 0b110 & 0b101
4
NOT
>>> ~ 0b101
-6
>>> ~ 0b100
-5
The NOT operation handles the sign bit, so a positive number becomes negative, and a negative number becomes positive.
XOR
>>> 0b111 ^ 0b101
2
>>> 0b111 ^ 0b100
3
An XOR operation results in 1 only if the two corresponding bits are different (one is 0 and the other is 1); otherwise, the result is 0.
This characteristic can be used for comparing differences. For example, to find how many bits need to be changed to transform 0b111
into 0b101
, you can use bin(0b111 ^ 0b101).count("1")
.
Bitwise operations in Python often have interesting applications, such as checking if a number is odd or even. You could use X % 2 == 1
or directly use the bitwise operation X & 1
.