Bit manipulation

  • char :

    • 1 bytes, 8 bits

    • ASCII: 0< char <127

  • int:

    • 4bytes, 32bits

  • double, float:

    • 8bytes, 32bits

1.Flip operation

char x = 'A' // 01000001
char y = ~x; // 10111110

2.And operation

char x = 'A';  // 01000001
char y = 'L';  // 01001100
char z = x & y;// 01000000

3.Or operation

4.XOR operation

  • 兩個同時等於0, 兩個不同時等於1

  • b ^ 11111111 = ~b

  • b ^ b = 0

5.Shift operation

6.Get the Nth bit

  • 用Nth為1的check bit做and運算, 再shift left

7.Set the Nth bit to 1

8.Print bits an integer

  • Shift it left sizeof(int)*8 - 1 times

9.Count the number of 1 bits

  • The simple way is very similar to the print bits example: O(N)

  • binary subtraction: n & (n - 1): O(1)

10.Reverse the bits in an integer

Last updated