简体   繁体   English

Python:将一个字节转换为二进制并移位它的位?

[英]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. 我想在Python中为学校项目将编码转换为另一种编码。 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 00000001 11001100 01010101等

to

00000011 10011000 10101010 and so on 00000011 10011000 10101010等

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: 您可以使用bitstring库,它允许对任意长位进行逐位运算,例如导入和移位二进制数:

>>> 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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