Advertisement
Guest User

Untitled

a guest
Oct 21st, 2019
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.65 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3. def bin(x):
  4. return "{0:b}".format(x)
  5.  
  6. def rs_one(x):
  7. """ Right Shift by 1 """
  8. return x >> 1
  9.  
  10. def ls_one(x):
  11. """ Left Shift by 1 """
  12. return x << 1
  13.  
  14. def incr_shift(x):
  15. """
  16. This is going to chop-off the last bit (LSB) in each iteration
  17. """
  18. for i in range(10):
  19. print(bin(x >> i))
  20.  
  21. def right_shift_reverse(x):
  22. """
  23. This will do the reverse. It will chop of all the bits, and then
  24. in each iteration, we will get a new bit that was present.
  25. This will also only start doing this from 7 (in this case).
  26. So we will never see the bits shifted by more than 7.
  27. """
  28. for i in range(8):
  29. print(bin(x), " >> (7 - {})".format(i), bin(x >> (7 - i)))
  30.  
  31. def extract_bits_right_to_left(x):
  32. """
  33. Okay, so we have a way to get first n bits from a byte (right_shift_reverse)
  34. And we have a way to truncate everything but the LSB from the input.
  35.  
  36. Combining them should give us *individual* bits, from MSB -> LSB order!
  37. """
  38.  
  39. for i in range(8):
  40. bit = x >> (7 - i) & 1
  41. print(bin(x), ">> (7 - {}) & 1 =".format(i), bit)
  42.  
  43. def extract_bits_left_to_right(x):
  44. for i in range(8):
  45. bit = (x >> i) & 1
  46. print(bin(x), ">> {}) & 1 =".format(i), bit)
  47.  
  48. def iter_bits(x):
  49. for i in range(8):
  50. print(bin(0x80 >> i))
  51.  
  52. if __name__ == '__main__':
  53. x = 68
  54. print(x, bin(x), ">> 1 =", bin(rs_one(x)), rs_one(x))
  55. print(x, bin(x), "<< 1 =", bin(ls_one(x)), ls_one(x))
  56. incr_shift(x)
  57. print('---')
  58. right_shift_reverse(x)
  59. print('BITS, RIGHT TO LEFT:')
  60. extract_bits_right_to_left(x)
  61. print('BITS LEFT TO RIGHT:')
  62. extract_bits_left_to_right(x)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement