将包含11位整数的字节数组强制转换为16位整数数组

3

我有一个表示11位整数的打包流的bytes对象或bytearray对象。(编辑:流是不带填充的11位大端整数。)

有没有一种相对高效的方法将其复制到16位整数流中?或者其他整数类型?

我知道ctypes支持位域,但我不确定它是否在这里对我有帮助。

我能否“滥用”标准库的某些部分,以便已经为其他目的进行了这样的位操作?

如果我必须使用cython,是否有一个好的实现可以处理可变位长度?即不仅限于11位输入,而是12、13等?


编辑:基于PM2 Ring答案的纯Python解决方案

def unpackIntegers(data, num_points, bit_len):
    """Unpacks an array of integers of arbitrary bit-length into a 
    system-word aligned array of integers"""
    # TODO: deal with native integer types separately for speedups
    mask = (1 << bit_len) - 1

    unpacked_bit_len = 2 ** ceil(log(bit_len, 2))
    unpacked_byte_len = ceil(unpacked_bit_len / 8)
    unpacked_array = bytearray(num_points * unpacked_byte_len)
    unpacked = memoryview(unpacked_array).cast(
        FORMAT_CODES[unpacked_byte_len])

    num_blocks = num_points // 8 

    # Note: zipping generators is faster than calculating offsets 
    #       from a block count
    for idx1_start, idx1_stop, idx2_start, idx2_stop in zip(
            range(0, num_blocks*bit_len, bit_len),
            range(bit_len, (num_blocks+1)*bit_len, bit_len),
            range(7, num_points, 8),
            range(-1, num_points-8, 8),
            ):
        n = int.from_bytes(data[idx1_start:idx1_stop], 'big')
        for i in range(idx2_start, idx2_stop, -1):
            unpacked[i] = n & mask
            n >>= bit_len
    # process left-over part (missing from PM2 Ring's answer)
    else:
        points_left = num_points % 8 
        bits_left = points_left * bit_len
        bytes_left = len(data)-num_blocks*bit_len
        num_unused_bits = bytes_left * 8 - bits_left

        n = int.from_bytes(data[num_blocks*bit_len:], 'big')
        n >>= num_unused_bits
        for i in range(num_points-1, num_points-points_left-1, -1):
            unpacked[i] = n & mask
            n >>= bit_len
    return unpacked
1个回答

2

可能有更有效的方法使用第三方库来完成这个任务,但以下是一种使用标准Python的方法。

unpack生成器按照块迭代其data参数,data可以是任何产生字节的可迭代对象。为了解包11位数据,我们读取11个字节的块,将这些字节组合成一个整数,然后将该整数切片成8个部分,因此每个部分将包含来自相应11个源位的数据。

def unpack(data, bitlen):
    mask = (1 << bitlen) - 1
    for chunk in zip(*[iter(data)] * bitlen):
        n = int.from_bytes(chunk, 'big')
        a = []
        for i in range(8):
            a.append(n & mask)
            n >>= bitlen
        yield from reversed(a)

# Test

# 0 to 23 in 11 bit integers, packed into bytes
data = bytes([
    0, 0, 4, 1, 0, 48, 8, 1, 64, 48, 7, 
    1, 0, 36, 5, 0, 176, 24, 3, 64, 112, 15, 
    2, 0, 68, 9, 1, 48, 40, 5, 64, 176, 23,
])

print(list(unpack(data, 11)))

输出

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23]

请注意,如果data的长度不是bitlen字节的倍数,则最后一部分数据将被忽略。这里的bitlen指的是比特长度。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接