Bit computing tips

  1. And calculating (&)

    • Parity is determined: x & 1 = 0 is even

    • x & (x - 1) The rightmost 1 to 0

      Can be used to detect a number is not a power of 2, if a number is a power of two, then it's only a binary 1, after an elimination, should return 1

    • x & (x +1) to the right of consecutive 1 becomes 0

  2. OR (|)

    • x | 1 will be the last one to 1
    • x | (x + 1) becomes the rightmost 0 1
    • x | (x - 1) to the right of continuous 0 to 1
  3. Exclusive-OR operation (^)

    • x ^ 1 last negated

    • x ^ x = 0

      Only one array number appears once, and the rest appear twice, all the numbers are exclusive or can be obtained only once the number

    • Data interchange

      int swap (int a, int b) {
          a ^= b;
          b ^= a;
          a ^= b;
      }
  4. Shift operation

    • x >> 1 to remove the last bit

    • x << 1 0 added at the end

    • x << 1 | 1 1 added at the end

    • Take the position x of y

      int get(int x, int y) { 
          return (x >> (y - 1)) & 1;
      } 

A write function, and the sum of two integers, requires the use of four arithmetic operations can not function symbol vivo

int Add(int num1, int num2)
    {
        while (num2) {
            int temp = num1 ^ num2;
            num2 = (num1 & num2) << 1;
            num1 = temp;
        }
        return num1;
    }

An integer that indicates the number of the output of the binary number 1 in. Wherein negative numbers complement representation

int  NumberOf1(int n) {
        int count = 0;
        while (n != 0) {
            ++count;
            n = (n - 1) & n;
        }
        return count;
     }

Absolute value

int abs(int n) //针对32位的int
{  
    return (n ^ (n >> 31)) - (n >> 31);  
} 
  • If n is a positive number, n >> 31 bits all equal to 0, a value equal to 0. Expressions into n ^ 0 - 0, n-equal;
  • If n is negative, n >> is equal to 1 for all 31 bits, which value is equal to -1. Expressions into (n ^ -1) + 1, it is well understood, is the negative inverse of its inverted complement plus 1, (n ^ -1) + 1 that do such a thing.

Guess you like

Origin www.cnblogs.com/gcheeze/p/11209639.html