Python: convert a byte to binary and shift its bits? -
i want convert encoding encoding in python school project. however, encoding translating add padding encoding on first bit.
how shift binary number sequence left one, goes from:
00000001 11001100 01010101 , on
to
00000011 10011000 10101010 , on
so end result's lowest bit former's highest bit number?
you can convert string 1 big integer , left-shift (and convert big integer string):
large_int = bytes2int(mystring) large_int <<= 1 mystring = int2bytes(large_int)
using e.g. simplistic implementation:
def bytes2int(str): res = ord(str[0]) ch in str[1:]: res <<= 8 res |= ord(ch) return res def int2bytes(n): res = [] while n: ch = n & 0b11111111 res.append(chr(ch)) n >>= 8 return ''.join(reversed(res)) bytes = 'abcdefghijklmnopqrstuv' assert int2bytes(bytes2int(bytes)) == bytes
Comments
Post a Comment