Calculation principle

Modern computers can only deal with binary data. Basic addition, subtraction, multiplication and division are all done through binary operations. Only the binary is not convenient program ape →_→ memory, then each immortal big guy on the unusual move. Assembly language appeared, A, B, C and other relatively advanced languages have also appeared.

Because binary is closer to hardware, it can be better optimized for hardware, which is why assembly is faster than C and other high-level languages most of the time. Of course, in high level language, we can also use bit operation to improve the performance of the program.

void test(int x)
{
    if (x & 1) {
        printf("Odd");
    } else {
        printf("Even"); }}Copy the code

See the specific principle below

An operator

operation The operator The sample
Left shift (low fill 0) << 0011 = > 0110
Right shift (positive numbers move right, use the complement 0 for high numbers, negative numbers move right, use the complement 1 for high numbers) >> 0110 = > 0011
Unsigned left shift (low zero complement) <<< 1111 = > 1110
Unsigned right shift (high fill 0) >>> 1111 = > 0111
Bitwise or | 0011 | 1011 = > 1011
Bitwise and & 0011&1011 => 1011
According to the not ~ 0011 = > 1100
Bitwise xor (same as zero, different as one) ^ 0011 ^ 1011 => 1000

Beg absolute value

int v; unsigned int r; Const mask = v >> sizeof(int) * char_bit-1; r = (v + mask) ^ mask;Copy the code

For example, +7(00000111) 8 bits, calculate mask=00000000;

(00000111 + 00000000) ^ 00000000 => 00000111
Copy the code

The absolute value of a positive number is itself!

If it is -7(11111001), calculate mask=11111111;

(11111001 + 11111111) ^ 11111111 => 00000111
Copy the code

Negative absolute value equals positive!

Judge parity

void test(int x)
{
    if (x & 1) {
        printf("Odd");
    } else {
        printf("Even"); }}Copy the code

The binary of 1 is 000… 00001; The digits above the first digit of any number with which the ampersand operation is performed become zeros. Since x is binary, the least significant 1 is odd and 0 is even.

Exchange value

Void swap(int x, int y) {x ^= y; y ^= x; x ^= y; }Copy the code

Modulus operation

int mod(int n, int s) { unsigned int d = 1 << s; // d is a power of 2 1, 2, 4, 8, 16, 32...returnn & (d - 1); // equivalent to n % s}Copy the code





Reference en.wikipedia.org/wiki/Assemb… Graphics.stanford.edu/~seander/bi…