Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.84 KB | None | 0 0
  1. Bit Manipulation
  2.  
  3. & - and - both values are 1
  4.  
  5. | - or - one or the other is 1
  6.  
  7. ^ - xor - if only one value is 1
  8.  
  9. ~ - not - flips the bit
  10.  
  11. << - left shift - shifts the bits left, same thing as multiplying by 2! COOL!
  12. 00010110 << 00000010 = 01011000
  13. 22 * 2 * 2 = 88
  14.  
  15. >> - right shift - shifts bits to the right, same thing as diving by 2, with rounding down! COOL!
  16. 00010110 >> 00000010 = 00000101
  17. 22 / 2 / 2 = 5
  18.  
  19. ------ Bit masking ------
  20. A mask is just a positional reference to the bit that needs to be set.
  21.  
  22. SETTING A BIT AT POSITION
  23.  
  24. x = 000000, 6 bits.
  25. If I want to clear the second bit (or the 4th column from the right) to 1, I make this mask:
  26. mask = 1 << 4 or mask = 1 << 000100
  27. x = x | mask or x |= mask, Which is 000000 | 010000
  28.  
  29. CLEARING A BIT AT POSITION
  30.  
  31. x = 001011, 6 bits.
  32. If I want to set the third bit (or the 3th column from the right) to 0, I make this mask:
  33. mask = 1 << 3 or mask = 1 << 000011
  34. x = x & ~mask or x &= ~mask
  35. x = 001011
  36. m = 001000
  37. ~m = 110111
  38. x&~m = 001011 & 110111 = 000011 = 3
  39.  
  40. FLIPPING A BIT
  41.  
  42. x = 001011, 6 bits
  43. If I want to flip the second bit (or 4th column from the right) to 1, I make this mask:
  44. mask = 1 << 4 or mask = 1 << 000100
  45. x = x ^ mask or x ^= mask.
  46.  
  47. TESTING IF A BIT IS SET OR NOT
  48.  
  49. x = 001011, 6 bits
  50. Testing the second bit (4th column from right, 1st column from left), I make this mask:
  51. mask = x >> 000100
  52. shifted = mask & 1
  53. Shifted will be 1 if set, 0 if not set
  54.  
  55. CHECK IF NUMBER IS EVEN OR ODD
  56.  
  57. x = 001011, 6 bits
  58. x & 1 == 0 or 001011 & 000001 = 000001
  59.  
  60. CHECK IF POWER OF TWO
  61.  
  62. x = 001011, 6 bits
  63. (x & x-1 == 0) or (001011 & 001011 - 000001) or (001011 & 001010 = 001010 which is not 0)
  64.  
  65. HOW MANY BITS ARE DIFFERENT BETWEEN TWO NUMBERS?
  66.  
  67. ```
  68. x = 0b001011
  69. y = 0b111001
  70. def how_many_different(x, y):
  71. dif = 1
  72. z = x ^ y
  73. for i in range(6):
  74. if (z>>i)&1=1
  75. dif+=1
  76. return dif
  77.  
  78. (how_many_different(x, y) == 3) is True
  79. ```
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement