Python brush questions: common binary operation (bit operation)

Time:2021-5-29

1. Variable value exchange

Title Description:In the premise of not using the third variable, the binary method is used to exchange the values of two integer variables.
Solution code:

>>> a = 1234
>>> b = 5678
>>> a = a ^ b
>>> b = a ^ b
>>> a = a ^ b
>>> print(a, b)
5678 1234

Conclusion:Swapping the values of two variables can be very simple in Python, such asa, b = b, aHowever, if you want to operate in binary mode, you can use the characteristic of XOR operation. From this algorithm, you can also get the characteristic of XOR operation: two integer value XOR can get an intermediate value, and the intermediate value and any original value can get the value of another variable by performing XOR operation again.

2. The lowest 1 is cleared

Title Description:For an integer value, in the binary representation, the lowest 1 of the integer value is changed to 0, and the values of other positions remain unchanged.
Solution code:

>>> x = 124
>>> bin(x)
'0b1111100'
>>> bin(x&(x-1))
'0b1111000'

Conclusion:This is also a common binary operation, using the formulax&(x-1)That’s it,&Is the binary and operation.

3. Get the lowest 1

Title Description:For an integer value, in the binary representation, only the lowest 1 is retained, and the rest of the values become 0.
Solution code:

>>> x = 86
>>> bin(x)
'0b1010110'
>>> bin(x&~(x-1))
'0b10'

Conclusion:This is also a common binary operation, using the formulax&~(x-1)That’s it,$For binary and operations,~Negate for binary.

4. Exchange two bits of the specified position

Title Description:For an integer value, in binary representation, the value of two bits of a specified position is exchanged.
Solution code:

def swap_bit(x, i, j):
    #If the i-th and j-th bits are the same, there is no need to swap them
    if ((x >> i) & 1) != ((x >> j) & 1):
        x ^= ((1 << i) | (1 << j))

    return x


x = 0b0101
i = 0
j = 1
print(bin(swap_ Bit (x, I, J)) # output: 0b110

Conclusion:This is also a common binary operation, using the formulaX ^ = ((1 < OK, ^ is binary XOR operation).

The problem and algorithm are from:Python programmer interview book.