Bit operation introduction and practical skills (I): Basics

Source: Internet
Author: User

What is bitwise operation?
All the numbers in the program are stored in binary form in computer memory. The bitwise operation is to directly operate the binary bit of the integer in the memory. For example, the and operation is a logical operator, but the and operation can be performed between integers. For example, if the binary value of 6 is 1011 and the binary value of 11 is, the result of 6 and 11 is 2, which is the result of the logical operation of the binary corresponding bit (0 indicates false, 1 indicates true, empty space is processed as 0 ):
110
& 1011
----------
0010 --> 2
Bitwise operations directly perform operations on memory data and do not need to be converted to decimal. Therefore, the processing speed is very fast. Of course, some people will say, what is the use of this speed? Computing 6 and 11 has no practical significance. This series of articles will show you what bitwise operations can do, some classic applications, and how to use bitwise operations to optimize your program.

BITs in Pascal and C
The following values of A and B are integers:
C language | PASCAL Language
------- + -------------
A & B | A and B
A | B | A or B
A ^ B | a XOR B
~ A | not
A <B | A SHL B
A> B | a shr B
Note that the logical operation and bitwise operator number in C are different. 520 | 1314 = 1834, but 520 | 1314 = 1, because both 520 and 1314 are equivalent to true in logical operation. The same ,! A and ~ A is also different.

Use of various bitwise operations
= 1. And =
The and operation is usually used for bitwise operations. For example, the result of a number and 1 is the last bit of the binary. This can be used to judge the parity of an integer. the last bit of binary is 0, which indicates that the number is an even number, and the last bit is 1, which indicates that the number is an odd number.

=== 2. Or operations ===
The or operation is usually used to assign values unconditionally on Binary location. For example, the result of a number or 1 is to forcibly change the last binary to 1. If you need to change the last bit of the binary to 0, you can subtract one after the number or 1. The actual meaning is to forcibly change the number to the nearest even number.

=== 3. XOR operations ===
The XOR operation is usually used to perform the inverse operation on a specific binary bit, because the difference or can be defined as follows: 0 and 1 are not the same or 0 is the same, or 1 is the opposite.
The inverse operation of XOR is itself. That is to say, the final result of two different or the same number remains unchanged, that is, (a xor B) xor B =. The XOR operation can be used for simple encryption. For example, if I want to say 1314520 to my mm, but I am afraid that others will know it, then both parties agree to use my birthday 19880516 as the key. 1314520 XOR 19880516 = 20665500, I will tell mm 20665500. MM calculates the value of 20665500 XOR 19880516 again and obtains 1314520, so she understands my attempt.
Next let's look at another thing. Define two symbols # And @ (why can't I find the character with a cross in that circle). These two symbols are inverse operations, that is, (x # Y) @ Y = x. Now, execute the following three commands in sequence. What is the result?
x <- x # y
y <- x @ y
x <- x @ y

After the first sentence is executed, X becomes x # Y. In the second sentence, the essence is Y <-X # Y @ Y. Because the # And @ operations are inverse, then the Y becomes the original X. In the third sentence, X is actually assigned (X # Y) @ X. If # has an exchange law, then after the value is assigned, X becomes the initial y. The result of these three statements is that the positions of X and Y are swapped.
Addition and subtraction are inverse operations, and addition satisfies the exchange law. Replace # With + and @ with-. we can write a SWAp process (Pascal) without a temporary variable ).
procedure swap(var a,b:longint);
begin
   a:=a + b;
   b:=a - b;
   a:=a - b;
end;

Okay. Didn't we say that XOR's inverse operation is itself? So we have a SWAp process that looks very strange:
procedure swap(var a,b:longint);
begin
   a:=a xor b;
   b:=a xor b;
   a:=a xor b;
end;

=== 4. Not operation ===
The not operation is defined to reverse all 0 and 1 in the memory. Be careful when using the not operation. You must note that the integer type has no symbols. If the object of not is an unsigned integer (which cannot represent a negative number), the obtained value is the difference between it and the upper bound of this type, because the number of unsigned types is represented in sequence from $0000 to $ FFFF. The following two programs (only different languages) return 65435.
var
   a:word;
begin
   a:=100;
   a:=not a;
   writeln(a);
end.

#include <stdio.h>
int main()
{
    unsigned short a=100;
    a = ~a;
    printf( "%d/n", a );    
    return 0;
}

If the not object is a signed integer, the situation is different. We will refer to it later in the "Storage of integers" section.

=== 5. SHL operations ===
A shl B indicates to convert a to binary and then shift B to the left (add B 0 at the end ). For example, if the binary value of 100 is 1100100, And the decimal value of 110010000 is 400, then 100 SHL 2 = 400. We can see that the value of a shl B is actually the power of B multiplied by a by 2, because adding 0 after the binary number is equivalent to multiplying this number by 2.
Generally, a SHL 1 is faster than a * 2 because the former is a more underlying operation. Therefore, replace the operation multiplied by 2 with a left shift.
Defining some constants may use the SHL operation. You can easily use 1 SHL 16-1 to represent 65535. Many algorithms and data structures require that the data size must be a power of 2. In this case, you can use SHL to define constants such as max_n.

=== 6. SHR operation ===
Similar to SHL, a shr B indicates that the binary shifts B places to the right (remove the last B bits), which is equivalent to dividing a by the B power of 2 (rounded up ). We often use SHR 1 to replace Div 2, such as binary search and heap insert operations. Using SHR instead of division can greatly improve the program efficiency. The binary algorithm of the maximum common divisor is divided by two operations to replace the surprisingly slow mod operation. The efficiency can be improved by 60%.

Simple Application of bit operations
Sometimes our program needs a small hash table to record the state. For example, we need 27 hash tables to calculate the number of each row, each column, and each small nine cells. In this case, we can record 27 integers smaller than 2 ^ 9. For example, a small nine cells with only 2 and 5 are represented by a number 18 (Binary 000010010), and a row in 511 State indicates that the row has been filled. When we need to change the status, we do not need to convert this number into binary and then convert it back, but directly perform a bit operation. During search, the status is expressed as an integer to better judge the weight.This questionThis is a classic example of bitwise computing acceleration in search. We will see more examples later.
The following lists some common binary bitwise conversion operations.

Function | example | bitwise operation
---------------------- + --------------------------- + --------------------
Remove the last digit | (101101-> 10110) | x SHR 1
Add 0 | (101101-> 1011010) | x SHL 1
Add 1 | (101101-> 1011011) | x SHL 1 + 1
Change the last digit to 1 | (101100-> 101101) | X or 1
Convert the last bit to 0 | (101101-> 101100) | X or 1-1
Last bitwise | (101101-> 101100) | x XOR 1
Change right K to 1 | (101001-> 101101, K = 3) | X or (1 SHL (k-1 ))
Change right K to 0 | (101101-> 101001, K = 3) | X and not (1 SHL (k-1 ))
Right K-bit inverse | (101001-> 101101, K = 3) | x XOR (1 SHL (k-1 ))
Last three digits | (1101101-> 101) | X and 7
Last K bit | (1101101-> 1101, K = 5) | X and (1 SHL k-1)
Right K bit | (1101101-> 1, K = 4) | x SHR (k-1) and 1
Turn the last K bit into 1 | (101001-> 101111, K = 4) | X or (1 SHL k-1)
Last K bit inversion | (101001-> 100110, K = 4) | x XOR (1 SHL k-1)
Change 1 on the right to 0 | (100101111-> 100100000) | X and (x + 1)
Change the first 0 from the right to 1 | (100101111-> 100111111) | X or (x + 1)
Change the continuous 0 on the right to 1 | (11011000-> 11011111) | X or (x-1)
1 in a row on the right | (100101111-> 1111) | (x XOR (x + 1) SHR 1
Remove the left of the first 1 from the right | (100101000-> 1000) | X and (x XOR (x-1 ))

The last one will be used in the tree array.

Hexadecimal representation in Pascal and C
In PASCAL, the $ symbol must be added before the hexadecimal number. In C, the 0x symbol must be added before the hexadecimal number. This will be frequently used in the future.

Integer Storage
The bitwise operations we mentioned earlier do not involve negative numbers. They all assume that these operations are performed on unsigned/word types (only positive integers are allowed. But how does the computer handle positive and negative integer types? The following two programs evaluate the storage mode of 16-bit integers (only in different languages ).
var
   a,b:integer;
begin
   a:=$0000;
   b:=$0001;
   write(a,' ',b,' ');
   a:=$FFFE;
   b:=$FFFF;
   write(a,' ',b,' ');
   a:=$7FFF;
   b:=$8000;
   writeln(a,' ',b);
end.

#include <stdio.h>
int main()
{
    short int a, b;
    a = 0x0000;
    b = 0x0001;
    printf( "%d %d ", a, b );
    a = 0xFFFE;
    b = 0xFFFF;
    printf( "%d %d ", a, b );
    a = 0x7FFF;
    b = 0x8000;
    printf( "%d %d/n", a, b );
    return 0;
}

The output values of the two programs are 0, 1, 2, and 1, 32767, and 32768. When the first two values are the smallest memory values and the middle two values are the largest memory values, the last two values are the boundary between the positive and negative numbers. From this, you can clearly see how the computer stores an integer: The computer uses $0000 to $ 7fff to represent the numbers 0 to 32767 in turn, the remaining $8000 to $ FFFF represent-32768 to-1 in sequence. The storage of 32-bit signed integers is similar. Note that you will find that the first part of the binary is used to represent positive and negative numbers, 0 indicates positive, and 1 indicates negative. Here is a problem: 0 is neither a positive nor a negative number, but it occupies the position of $0000. Therefore, the number of positive numbers in a signed integer range is one less than that of a negative number. After performing the not operation on a signed number, the change of the highest bit will lead to positive and negative inversion, and the absolute value of the number will be 1 different. That is to say, not a actually equals-A-1. This integer storage method is called "complement ".

There are two more sentences.
Matrix67 original
Please indicate the source of the post

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.