Advertisement
dungdq

Bit manipulation

Jun 19th, 2021 (edited)
647
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.44 KB | None | 0 0
  1. /*
  2. **Bitwise operator has the least priority in processing equation**
  3. +++++++++++++++++++++++++++++++
  4. & - and
  5. 1 & 1 = 1
  6. 0 & 1 = 0
  7. 1 & 0 = 0
  8. 0 & 0 = 0
  9. Example:
  10. 13 (1101) & 4 (0100) = 4
  11. Explanation:
  12. 1101
  13. 0100
  14. ----
  15. 0100
  16. +++++++++++++++++++++++++++++++
  17. ^ - xor
  18. 1 ^ 1 = 0
  19. 0 ^ 1 = 1
  20. 1 ^ 0 = 1
  21. 0 ^ 0 = 0
  22. Example:
  23. 13 (1101) ^ 4(0100) = 9
  24. Explanation:
  25. 1101
  26. 0100
  27. ----
  28. 1001
  29. +++++++++++++++++++++++++++++++
  30. | - or
  31. 1 | 1 = 1
  32. 0 | 1 = 1
  33. 1 | 0 = 1
  34. 0 | 0 = 0
  35. Example:
  36. 13 (1101) | 4(0100) = 13
  37. Explanation:
  38. 1101
  39. 0100
  40. ----
  41. 1101
  42. +++++++++++++++++++++++++++++++
  43. ~ - not // uncommon
  44. ~1 = 0
  45. ~0 = 1
  46. Example:
  47. ~5 (00000000000000000000000000000101) = -6 (11111111111111111111111111111010)
  48. Integer is stored in computer by 32 bits.
  49. +++++++++++++++++++++++++++++++
  50. << - left shift
  51. Example: 3 (11) << 2 = 12 (1100)
  52. +++++++++++++++++++++++++++++++
  53. >> - right shift
  54. Example: 11 (1011) >> 2 = 2 (10)
  55. */
  56.  
  57. // Important
  58. int getBit(int x, int k) {
  59.     return (x >> k) & 1;
  60. }
  61. // usually used as  
  62. #define BIT(x,k) (((x) >> k) & 1)
  63.  
  64. // Important
  65. int setBit(int x, int k) {
  66.     return x | (1 << k);
  67. }
  68.  
  69. int offBit(int x, int k) {
  70.     return x & (~(1 << k));
  71. }
  72.  
  73. int flipBit(int x, int k) {
  74.     return x ^ (1 << k);
  75. }
  76. // for all functions above, if x is a long long variable, use 1LL << k instead of 1 << k.
  77.  
  78. // __builtin_popcount(x) return number of 1s in binary representation of x, for x in int
  79. // for long long x, using __builtin_popcountll(x)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement