02 bit operation

Reprinted from Datawhale open source learning library

https://github.com/datawhalechina/team-learning-program/tree/master/PythonLanguage

Bit operation

1. Original code, inverse code and complement

Binary has three different representations: original code, one's complement and complement. The computer uses complement to represent it .

Original code : is its binary representation (note that the highest bit is the sign bit).

00 00 00 11 -> 3
10 00 00 11 -> -3

Inverse code : The inverse code of a positive number is the original code, and the inverse code of a negative number is the sign bit unchanged, and the remaining bits are inverted (corresponding to the inverse of the positive number by bit).

00 00 00 11 -> 3
11 11 11 00 -> -3

Complement : The complement of a positive number is the original code, and the complement of a negative number is the complement +1.

00 00 00 11 -> 3
11 11 11 01 -> -3

Sign bit : The highest bit is the sign bit, 0 means positive number, 1 means negative number. In the bit operation, the sign bit also participates in the operation.

2. Bitwise non-operation ~

~ 1 = 0
~ 0 = 1

~The numcomplement of all negated 0 and 1 (0 to 1, 1 to 0) bit signed integer with a sign in the ~calculation will also negated.

00 00 01 01 -> 5
~
---
11 11 10 10 -> -6

11 11 10 11 -> -5
~
---
00 00 01 00 -> 4

3. Bitwise and operation &

1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0

Only when both corresponding bits are 1.

00 00 01 01 -> 5
&
00 00 01 10 -> 6
---
00 00 01 00 -> 4

4. Bitwise OR operation |

1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0

As long as one of the two corresponding bits is 1, it is 1

00 00 01 01 -> 5
|
00 00 01 10 -> 6
---
00 00 01 11 -> 7

5. Bitwise XOR operation ^

1 ^ 1 = 0
1 ^ 0 = 1
0 ^ 1 = 1
0 ^ 0 = 0

Only when two corresponding bits are different is 1

00 00 01 01 -> 5
^
00 00 01 10 -> 6
---
00 00 00 11 -> 3

The nature of the exclusive OR operation: satisfy the commutative law and associative law

A: 00 00 11 00
B: 00 00 01 11

A^B: 00 00 10 11
B^A: 00 00 10 11

A^A: 00 00 00 00
A^0: 00 00 11 00

A^B^A: = A^A^B = B = 00 00 01 11

6. Left shift operation by bit<<

num << iThe numbinary representation leftward movement ivalue obtained by bit.

00 00 10 11 -> 11
11 << 3
---
01 01 10 00 -> 88 

7. Right shift operation by bit >>

num >> iThe numbinary representation is moved rightward ia value obtained by bit.

00 00 10 11 -> 11
11 >> 2
---
00 00 00 10 -> 2 

8. Use bit operations to achieve fast calculations

Pass <<, >>quickly calculate the multiple of 2 problem.

n << 1 -> 计算 n*2
n >> 1 -> 计算 n/2,负奇数的运算不可用
n << m -> 计算 n*(2^m),即乘以 2 的 m 次方
n >> m -> 计算 n/(2^m),即除以 2 的 m 次方
1 << n -> 2^n

Through the ^rapid exchange of two integers.

a ^= b
b ^= a
a ^= b

By a & (-a)quick access to athe last is an integer from 1 location.

00 00 01 01 -> 5
&
11 11 10 11 -> -5
---
00 00 00 01 -> 1

00 00 11 10 -> 14
&
11 11 00 10 -> -14
---
00 00 00 10 -> 2

9. Use bit operations to implement integer sets

The binary representation of a number can be seen as a set (0 means not in the set, 1 means in the set).

For example set {1, 3, 4, 8}may be represented as 01 00 01 10 10bits and the corresponding operation can also be viewed as a collection operation.

Operation of elements and collections:

a | (1<<i)  -> 把 i 插入到集合中
a & ~(1<<i) -> 把 i 从集合中删除
a & (1<<i)  -> 判断 i 是否属于该集合(零不属于,非零属于)

Operations between sets:

a 补   -> ~a
a 交 b -> a & b
a 并 b -> a | b
a 差 b -> a & (~b)

Note: Integers exist in the form of complement in the memory, and the output is naturally output in complement.

[Example] C# language outputs negative numbers.

class Program
{
    
    
    static void Main(string[] args)
    {
    
    
        string s1 = Convert.ToString(-3, 2);
        Console.WriteLine(s1); 
        // 11111111111111111111111111111101
        
        string s2 = Convert.ToString(-3, 16);
        Console.WriteLine(s2); 
        // fffffffd
    }
}

[Example] Python bin()output.

print(bin(3))  # 0b11
print(bin(-3))  # -0b11

print(bin(-3 & 0xffffffff))  
# 0b11111111111111111111111111111101

print(bin(0xfffffffd))       
# 0b11111111111111111111111111111101

print(0xfffffffd)  # 4294967293

Is it very subversive, we can see from the results:

  • binA negative number (decimal representation) in Python , the output is the binary representation of its original code plus a minus sign, a giant pit.
  • Integers in Python are stored in one's complement form.
  • Integers in Python are not limited in length and will not overflow.

Therefore, in order to obtain the complement of a negative number (decimal representation), you need to manually AND with the hexadecimal number 0xffffffffby bitwise AND operation, and then give it bin()to the output, and get the complement of the negative number.


Practice questions :

Leetcode Exercise 136. Numbers that only appear once

Given an array of non-empty integers, except for an element that appears only once, every other element appears twice. Find the element that appears only once.

Try to use bit operations to solve this problem.

Title description:

"""
Input file
example1: [2,2,1]
example2: [4,1,2,1,2]

Output file
result1: 1
result2: 4
"""



class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        
     # your code here

Guess you like

Origin blog.csdn.net/Han_Panda/article/details/113091920