从8位数组转换为5位数组

2024-09-26 22:53:07 发布

您现在位置:Python中文网/ 问答频道 /正文

python有没有简单的方法将8位转换为5位。目前我正在使用以下代码:

def convertbits(data, frombits, tobits, pad=True):
    acc = 0
    bits = 0
    ret = []
    maxv = (1 << tobits) - 1
    max_acc = (1 << (frombits + tobits - 1)) - 1
    for value in data:
        if value < 0 or (value >> frombits):
            return None
        acc = ((acc << frombits) | value) & max_acc
        bits += frombits
        while bits >= tobits:
            bits -= tobits
            ret.append((acc >> bits) & maxv)
    if pad:
        if bits:
            ret.append((acc << (tobits - bits)) & maxv)
    elif bits >= frombits or ((acc << (tobits - bits)) & maxv):
        return None
    return ret

有更好的办法吗?你知道吗

编辑:输出应该是5位整数的列表,在过程中不会丢失任何数据

它的工作原理如下:

>>> hello = [ord(letter) for letter in 'hello']
>>> hello
[104, 101, 108, 108, 111]
>>> convertbits(hello, 8, 5)
[13, 1, 18, 22, 24, 27, 3, 15]
>>> 

Tags: hellofordatareturnifvaluemaxbits
1条回答
网友
1楼 · 发布于 2024-09-26 22:53:07

嗯,这是相对内存效率低,因为它将个别位转换为字符串,但它似乎工作:

import itertools  

def convertbits(data, From, To):
    bits_orig = itertools.chain.from_iterable(bin(n)[2:].zfill(From) for n in data)

    chunks = iter(lambda: ''.join(itertools.islice(bits_orig, To)), '')

    return [int(n, 2) for n in chunks]


print(convertbits(b'hello', 8, 5))
print([13, 1, 18, 22, 24, 27, 3, 15])

一旦得到一个数字位流(bits_orig),就可以简单地将这个流分割成等长的块(chunks)(这个版本不做填充,但实现起来相当简单)并将1和0的字符串转换回数字。你知道吗


如果你只处理8位数字,这里有一个算法是8.5(!)比上面的快几倍:

from collections import deque 

def convert8bits(data, To):
    number = int.from_bytes(data, 'big')

    ret = deque()
    th = (1 << To) - 1
    while number:
        ret.appendleft(number & th)
        number >>= To

    return ret

相关问题 更多 >

    热门问题