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]
>>>
嗯,这是相对内存效率低,因为它将个别位转换为字符串,但它似乎工作:
一旦得到一个数字位流(
bits_orig
),就可以简单地将这个流分割成等长的块(chunks
)(这个版本不做填充,但实现起来相当简单)并将1和0的字符串转换回数字。你知道吗如果你只处理8位数字,这里有一个算法是8.5(!)比上面的快几倍:
相关问题 更多 >
编程相关推荐