Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- def bin(x):
- return "{0:b}".format(x)
- def rs_one(x):
- """ Right Shift by 1 """
- return x >> 1
- def ls_one(x):
- """ Left Shift by 1 """
- return x << 1
- def incr_shift(x):
- """
- This is going to chop-off the last bit (LSB) in each iteration
- """
- for i in range(10):
- print(bin(x >> i))
- def right_shift_reverse(x):
- """
- This will do the reverse. It will chop of all the bits, and then
- in each iteration, we will get a new bit that was present.
- This will also only start doing this from 7 (in this case).
- So we will never see the bits shifted by more than 7.
- """
- for i in range(8):
- print(bin(x), " >> (7 - {})".format(i), bin(x >> (7 - i)))
- def extract_bits_right_to_left(x):
- """
- Okay, so we have a way to get first n bits from a byte (right_shift_reverse)
- And we have a way to truncate everything but the LSB from the input.
- Combining them should give us *individual* bits, from MSB -> LSB order!
- """
- for i in range(8):
- bit = x >> (7 - i) & 1
- print(bin(x), ">> (7 - {}) & 1 =".format(i), bit)
- def extract_bits_left_to_right(x):
- for i in range(8):
- bit = (x >> i) & 1
- print(bin(x), ">> {}) & 1 =".format(i), bit)
- def iter_bits(x):
- for i in range(8):
- print(bin(0x80 >> i))
- if __name__ == '__main__':
- x = 68
- print(x, bin(x), ">> 1 =", bin(rs_one(x)), rs_one(x))
- print(x, bin(x), "<< 1 =", bin(ls_one(x)), ls_one(x))
- incr_shift(x)
- print('---')
- right_shift_reverse(x)
- print('BITS, RIGHT TO LEFT:')
- extract_bits_right_to_left(x)
- print('BITS LEFT TO RIGHT:')
- extract_bits_left_to_right(x)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement