# 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 as`a, b = b, a`However, 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 formula`x&(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 formula`x&~(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 formula`X ^ = ((1 < OK, ^ is binary XOR operation).`

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

## Programming Xiaobai must understand the network principle

How is the network composed? Why can we easily surf the Internet now?Whether you are a computer major or not, you may always have such questions in your heart!And today we will solve this matter and tell you the real answer! Basic composition of network First, let’s look at this sentence Connect all computers together […]