简体   繁体   中英

Python: convert a byte to binary and shift its bits?

I want to convert an encoding to another encoding in Python for a school project. However, the encoding I am translating from will add a padding to its encoding on the first bit.

How do I shift an binary number sequence to the left by one, so that it goes from:

00000001 11001100 01010101 and so on

to

00000011 10011000 10101010 and so on

so the end result's lowest bit will be the former's highest bit number?

You can use the << operator to left shift, and conversely >> will right shift

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

You could use the bitstring library which allows for bitwise operations on arbitrarily long bitstrings eg to import and shift your binary number:

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

You can convert the string to one big integer and then do the left-shift (and then convert the big integer back into a string):

large_int = bytes2int(mystring)
large_int <<= 1
mystring = int2bytes(large_int)

using eg this simplistic 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM