在Python中,如何从字节数组中提取任意的位序列并将其转换为整数?

hfyxw5xn  于 2022-10-22  发布在  Python
关注(0)|答案(2)|浏览(186)

我正在寻找一个相当于https://www.npmjs.com/package/bit-sequence的python。
也就是说,我需要一个函数,它接受一些“字节”,一些与整数位索引相对应的“开始”值来开始提取(而不是字节索引),一些“长度”值来对应于从字节数组中提取的位数

svgewumm

svgewumm1#

我认为这解决了您的问题,有关python中位操作的更多信息,请查看此链接->https://realpython.com/python-bitwise-operators/#bit-python中的字符串

def bytes_extraction(bytes, start, length):
    bytes = bin(bytes)
    result = bytes[start:start+length]
    result = int(result, 2)
    return  result

bits = 0b101010 
response = bytes_extraction(bytes=bits , start=2, length=4)
print(response)
bvjveswy

bvjveswy2#

下面是一个答案,以您链接的页面为例:

def bytes_extraction(bytes, start, length):

    # Converting a byte to an 8-length binary string
    def format_byte(byte):
        fbyte = bin(byte)[2:]
        fbyte = str(0) * (8 - len(fbyte)) + fbyte
        return fbyte

    # Converting the bytes array into one long bit string
    binstring = "".join([format_byte(byte) for byte in bytes])

    # Converting the bitstring to a base 10 int
    ret_byte = int("0b"+binstring[start:start+length], 2)

    return  ret_byte

example=[ 0b00010101, 0b10101000, 0b00000000, 0b00000000 ]
response = bytes_extraction(example , 7, 11)
print(response)
1696

相关问题