Python: convert byte to binary and shift its bits?
I want to convert encoding to another encoding in Python for a school project. However, the encoding I translated will add padding to its encoding on the first bit.
How to change the sequence of binary numbers to the left by one so that it starts with:
00000001 11001100 01010101 etc.
to
00000011 10011000 10101010 etc.
so the least significant bit of the final result will be the first highest bit number?
+3
source to share
3 answers
You can convert a string to one large integer and then shift to the left (and then convert the large integer back to a string):
large_int = bytes2int(mystring) large_int <<= 1 mystring = int2bytes(large_int)
using for example this simplified implementation:
def bytes2int(str):
res = ord(str[0])
for 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
-1
source to share