Binary, bit operations and mask operations, mouse test example

1. Binary

Binary is a number system based on two numbers, 0 and 1. It can represent two states, on and off. All information entered into the computer must eventually be converted into binary data. Currently, the ASCII code is commonly used. The most basic unit is bit.
In computer science, binary is the most commonly used number system because all data inside a computer is stored and processed in binary form.

In binary, each digital bit is called a bit, which can be 0 or 1. The bit positions increase from right to left, and the value of each position is a power of 2. For example, the weight of the rightmost bit is 2 0, which is 1; the weight of the second bit is 2 1, which is 2; the weight of the third bit is 2^2, which is 4, and so on.

Using binary, a variety of data can be represented and processed, including integers, decimals, characters, images, etc. For example, the integer 10 can be represented as 1010 in binary, where 1 means that the corresponding bit is 1 and 0 means that the corresponding bit is 0.

Binary can also perform various operations, including addition, subtraction, multiplication and division. These operations are similar to decimal operations, except that the numbers used are 0 and 1.

2. Bit operations

Binary bit operations are bit-by-bit logical operations on binary numbers, including bitwise AND (&), bitwise OR (|), bitwise XOR (^), bitwise negation (~) and other operations.

2.1 Binary bit operators and their examples

  1. AND operation (&): When the numbers on the two corresponding bits are both 1, the result is 1, otherwise it is 0.
    Example:
   1101 & 1011 = 1001
  1. Or operation (|): When one of the two numbers in the corresponding bits is 1, the result is 1, otherwise it is 0.
    Example:
1101 | 1011 = 1111
  1. XOR operation (^): If the numbers on the two corresponding bits are different, the result is 1, and if they are the same, the result is 0.
    Example:
1101 ^ 1011 = 0110
  1. Not operation (~): negates each bit of a binary number.
    Example:
~1101 = 0010
  1. Left shift operation (<<): Shifts all bits of a binary number to the left by the specified number of digits.
    Example:
1101 << 2 = 10100
  1. Right shift operation (>>): Shifts all bits of a binary number to the right by the specified number of digits.
    Example:
1101 >> 2 = 0011

3. Binary example as a poison test mouse

Binary is very powerful and plays a very significant role in some aspects. The following is a small chestnut about binary:

  • Rats test poison

Insert image description here
Question:
There are 100 bottles of water, one of which is poisonous. The mice will die after 24 hours if they taste the poisonous water. How many mice are needed to identify which bottle of water is poisonous after 24 hours?
Answer:
Logically speaking, there should be 100 of them, so they can definitely be identified. But the problem is 至少要多少只可以鉴别出, we want the minimum, so we definitely can’t fill in 100 directly.

This problem can be solved cleverly with the help of binary operations.

In this way, let's simplify the problem first: Suppose there are only 8 bottles of water, one of which is poisonous, as follows:
Insert image description here
Suppose the water is numbered (based on binary calculation):
Insert image description here
After matrix transposition, it becomes:
Insert image description here
Find four white mice, according to the water number In order, the mice were named Rat Guest No. 1, Rat Guest No. 2, Rat Guest No. 3, and Rat Guest No. 4.
Drink the water with the corresponding water number in turn, observe it for 24 hours, find the corresponding number in the picture above according to the status (dead is 1, alive is 0), and then convert the binary to decimal, you can figure out which bottle of water is poisonous.
Insert image description here
Therefore, when there are 8 bottles of water and one of them is poisonous, only 4 mice are needed to detect which bottle is poisonous.
Expand the topic to 100 bottles of water.
2 raised to the 6th power is 64, and 2 raised to the 7th power is 128. Therefore, according to the above algorithm, it can be concluded that 7 mice are needed.
Assume (each bottle of water has a different number):
Insert image description here
Matrix transposition:
Insert image description here
Next is the white mouse and the corresponding water. Based on the living status of the white mouse, you can determine which bottle of water is poisonous.
Insert image description here

4. Mask operation

Mask operation refers to using bit operators to set or clear binary bits at specific positions.

  1. Set a certain position to 1: Use the bitwise OR operator (|) to perform a bitwise OR operation on the bit to be set and the current value.
    For example, set bit 3 to 1:
int value = 4;  // 二进制表示为00000100
value = value | (1 << 2);  // 将第3位设置为1,结果为00000100 | 00000100 = 00000100
  1. Clear a certain position to 0: Use the bitwise AND operator (&) to invert the bit to be cleared and perform a bitwise AND operation with the current value.
    For example, clear bit 5 to 0:
int value = 22;  // 二进制表示为00010110
value = value & ~(1 << 4);  // 将第5位清除为0,结果为00010110 & 11101111 = 00000110
  1. Switch the value of a certain position: Use the bitwise XOR operator (^) to perform a bitwise XOR operation between the bit to be switched and the current value.
    For example, to toggle the value of bit 2:
int value = 10;  // 二进制表示为00001010
value = value ^ (1 << 1);  // 切换第2位的值,结果为00001010 ^ 00000010 = 00001000
  1. Check whether a certain bit is 1: Use the bitwise AND operator (&) to perform a bitwise AND operation on the bit to be checked and the current value to determine whether the result is 0.
    For example, check if bit 7 is 1:
int value = 127;  // 二进制表示为01111111
int mask = 1 << 6;  // 设置掩码为第7位的1,即01000000
int result = value & mask;  // 结果为01111111 & 01000000 = 01000000
if(result != 0) {
    
    
    // 第7位为1
} else {
    
    
    // 第7位为0
}

5. Get a certain number of masks

There are two ways to get the mask from No. 1 to No. 1:

  • method one:
// 比如取第3位到第7位的掩码,就是设置第3位到第7位为1
// 掩码: 11111000
// 往左偏移7+1位 - 往左偏移3位 = 7-3位都是1
int mask = (1 << 8) - (1 << 3);

In order to verify whether the result is correct, directly output the converted value of "11111000" into decimal:
image.png

  • Method 2:
    Usebitset
	// 需引入头文件<bitset.h>
    std::bitset<8> mask(0);
    for(int i = 0; i < mask.size(); ++i)
    {
    
    
        if( i <= 7 && i >= 3)
        {
    
    
            mask[i] = 1;
        }
    }
    std::cout << mask << std::endl;

The result is as follows:
image.png

6 Conclusion

Bit operators can be used to perform various operations such as masking, clearing bits, setting bits, flipping bits, etc.
In actual programming, bit operations are often used in scenarios such as bit operations, optimization algorithms, and processing of binary data, which can improve efficiency and flexibility.

明天就要见对方家长了,好忐忑啊,毕竟是我先打的他们家小孩

Guess you like

Origin blog.csdn.net/MrHHHHHH/article/details/135296413