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


You can use operator <<

to shift left and vice versa, >>

shift right



>>> x = 7485254
>>> bin(x)
'0b11100100011011101000110'
>>> bin(x << 1)
'0b111001000110111010001100'

      

+3


source


You can use the bitstring library which allows you to perform bitwise operations on arbitrarily long bit strings, eg. to import and change the binary number:

>>> import bitstring
>>> bitstring.BitArray(bin='0b11100100011011101000110') << 1
BitArray('0b11001000110111010001100')

      

+1


source







All Articles