A brief introduction to bit operation and its usage skills

Source: Internet
Author: User
Tags greatest common divisor

Transfer from http://www.matrix67.com/blog/archives/263

The log of bit arithmetic written at the end of last year is one of the few popular articles in this blog, and many people want me to keep perfecting that article. Later, I saw a lot of other information, learned more about the bit operation of knowledge, with the idea of re-organizing the bit arithmetic skills. From today onwards I began to write this series of bit operations to explain the article, rather than the original article follow-up, rather than a remake. Of course, first of all, I started from the most basic things.

What is a bitwise operation?
All the numbers in the program are stored in binary form in the computer's memory. Bitwise arithmetic is the direct operation of an integer in memory bits. For example, an and operation is inherently a logical operator, but an and operation can also be performed between integers and integers. For example, the binary of 6 is the binary of the 110,11 is 1011, then the result of 6 and 11 is 2, which is the result of the logical operation of the binary corresponding bit (0 means that false,1 is true, the vacancy is treated as 0):
110
and 1011
———-
0010–> 2
Because bit arithmetic operates directly on memory data, it does not need to be converted to decimal, so processing is very fast. Of course some people will say, this is fast what is the use, calculate 6 and 11 no practical meaning ah. This series of articles will tell you what the bit operations can do, what the classic applications are, and how to optimize your program with bit arithmetic.


bit operation symbols in Pascal and C
The following both A and B are integer types:
C language | Pascal language
——-+ ————-
A & B | A and B
A |  B | A or B
a ^ B | A XOR B
~a | Not a
A << B | A SHL b
A >> B | A SHR b
Note that the logical operation and the bit operation symbols in C are different. 520|1314=1834, but 520| | 1314=1, because 520 and 1314 are equivalent to true for logical operations. Similarly, there are differences between!a and ~a.


use of various bit operations
= = = 1. and operation = = =
The and operation is typically used for binary take operations, such as the result of a number and 1, which is the last digit of the binary. This can be used to determine the parity of an integer, the last digit of the binary is 0 to indicate that the number is even, and the lowest of 1 indicates that the number is odd.

= = = 2. or operation = = =
An OR operation is usually used for unconditional assignment on a binary location, such as the result of a number or 1, which forcibly turns the binary lowest to 1. If you need to change the last binary to 0, the number or 1 will be reduced by one, the practical significance is to force this number to the nearest even.

= = = 3. XOR operation = = =
The XOR operation is typically used to reverse a particular one of the binary, because XOR can be defined as: 0 and 1 XOR 0 are unchanged, XOR or 1 are reversed.
The inverse of the XOR operation is itself, that is to say, two times or the same number end result is unchanged, i.e. (a XOR b) xor B = A. The XOR operation can be used for simple encryption, such as I want to say to my mm 1314520, but afraid of others know, so the two sides agreed to take my birthday 19880516 as a key. 1314520 xor 19880516 = 20665500, I will tell the 20665500 mm. MM again calculates the value of 20665500 xor 19880516 and gets 1314520, so she understands my intentions.
Let's look at another thing. Define two symbols # and @ (how can I not find the character that has a fork in the circle), the two symbols are inverse each other, that is (x # y) @ y = x. Now execute the following three commands sequentially, what is the result?
x <- x # y
y <- x @ y
x <- x @ y

After executing the first sentence, x becomes x # Y. Then the second sentence is actually y <-x # y @ y, because # and @ are inverse each other, then y becomes the original x. In the third sentence, X is actually assigned to (x # y) @ x, and if the # operation has an Exchange law, then x becomes the original y when the value is assigned. The result of these three sentences is that the positions of X and Y are interchanged.
Addition and subtraction are mutually inverse, and addition satisfies the commutative law. Replace # with + and replace @-we can write a swap process (Pascal) that does not require a temporary variable.
procedure swap(var a,b:longint);
begin
   a:=a + b;
   b:=a - b;
   a:=a - b;
end;

Okay, just not to say that Xor's inverse is itself? So we have a seemingly bizarre swap process:
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 negate all 0 and 1 in memory. Use the not operation with extreme caution, and you need to be aware that the integer type has no symbols. If the object of not is an unsigned integer (which cannot represent a negative number), then the resulting value is the difference between it and the upper bound of the type, because the numbers of unsigned types are represented by $0000 to $FFFF. The following two programs (different languages only) 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( "%dn", a );    
    return 0;
}

If the object of not is a signed integer, the situation is different and we will refer to it later in the "Storage of integer type" subsection.

= = = 5. SHL Operation = = =
A SHL B means to shift A to the binary and left B bit (add B 0 at the back). For example, 100 binary is 1100100, and 110010000 turns to decimal is 400, then SHL 2 = 400. As can be seen, the value of a SHL B is actually a multiplied by 2 of the B-side, because adding a 0 after the binary number is equal to the number multiplied by 2.
It is generally considered that a SHL 1 is faster than a * 2, because the former is more of a lower level of operation. So multiply the 2 in your program by using one of the left shifts instead.
Defining some constants may use the SHL operation. You can conveniently use 1 SHL 16–1 to represent 65535. Many algorithms and data structures require a power of 2 to scale, and you can use SHL to define constants such as Max_n.

= = = 6. SHR operation = = =
Similar to SHL, a shr b represents a binary right shift B-bit (minus the last B-bit), which is equivalent to a divided by 2 of the B-squared (rounding). We also often use SHR as a substitute for Div 2, such as binary lookup, heap insert operations, and so on. A way to replace the division operation with SHR can greatly improve the efficiency of the program. The greatest common divisor binary algorithm uses the 2 operation instead of the surprisingly slow mod operation, which can increase the efficiency by 60%.


simple application of bit arithmetic
Sometimes our program needs a small hash table to record the status. For example, when doing Sudoku we need 27 hash tables to count the number of each row, each column, and every small nine lattice. At this point, we can record with 27 integers less than 2^9. For example, a small nine gongge filled with only 2 and 5 is represented by the number 18 (binary 000010010), and a line with a status of 511 indicates that the line is filled. We do not need to turn this number into binary modification and then go back, but we will do the bit operation directly when we need to change the state. When searching, it is better to put the status as an integer in order to perform the operation of the sentence weight. This problem is a classic example of using bit arithmetic acceleration in search. We'll see more examples in the future.
The following is a list of some common bits transformation operations.

Features |    Example | Bit arithmetic
———————-+ ————————— + —————— –
Remove the last one | (101101->10110) | X SHR 1
Add a 0 at the end | (101101->1011010) | X SHL 1
Add a 1 at the end | (101101->1011011) | X SHL
Turn the last one into 1 | (101100->101101) | X or 1
Turn the last one into 0 | (101101->101100) | X or 1-1
Last one to take back | (101101->101100) | X XOR 1
Turn the right number k bit into 1 | (101001->101101,k=3) | X or (1 SHL (k-1))
Turn the right number K bit into 0 | (101101->101001,k=3) | X and not (1 SHL (k-1))
Right number k-position Inverse | (101001->101101,k=3) | X XOR (1 SHL (k-1))
Take the last three bits | (1101101->101) | X and 7
Take the last K-bit | (1101101->1101,k=5) | X and (1 SHL k-1)
Take the right number 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)
End K-Position Inversion | (101001->100110,k=4) | X XOR (1 SHL k-1)
Turn the right continuous 1 into 0 | (100101111->100100000) | X and (X+1)
Turn the first 0 from right to 1 | (100101111->100111111) | x or (x+1)
Turn the right continuous 0 into 1 | (11011000->11011111) | x or (X-1)
Take the right continuous 1 | (100101111->1111) | (x xor (x+1)) SHR 1
Remove right from the left of the first 1 | (100101000->1000) | X and (x xor (X-1))

This last one will be used in a tree array.


16 binary representations in Pascal and C
Pascal needs to be preceded by a $16 number notation, and C needs to be represented by the front plus 0x. We'll use it a lot later.

storage of integer types
None of the bitwise operations we mentioned earlier involve negative numbers, assuming that the operations are performed on the Unsigned/word type (integer type that can only represent positive numbers). But how does a computer handle an integer type with positive and negative symbols? The following two programs are all about how to store a 16-bit integer (only language is different).
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 %dn", a, b );
    return 0;
}

The output of both programs is 0 1-2-1 32767-32768. When the first two numbers are the lowest memory value, the middle two is the maximum memory value, the last output of the two number is a positive and negative boundary. From this you can clearly see how the computer stores an integer: The computer uses $0000 to $7FFF to represent 0 to 32767 of the number, and the remaining $8000 to $FFFF in turn represent the number 32768 to-1. A 32-bit signed integer is also stored in a similar manner. A little attention you will find that the first digit of the binary is used to denote the sign, 0 means positive, and 1 is negative. Here's a question: 0 is neither positive nor negative, but it occupies the position of the $0000, so the signed integer type range is one less than the negative number. When a not operation is performed on a signed number, the change in the highest bit will result in positive or negative reversal, and the absolute value of the number will be 1. In other words, not a is actually equal to-a-1. This integer storage method is called "complement".

Introduction to

(GO) bit operations and tips for using them

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.