繁体   English   中英

使用Python从字符串中提取2位整数

[英]Extracting 2 bit integers from a string using Python

我正在使用python通过UDP接收字符串。 我需要从字符串中的每个字符中提取4对位,并将它们转换为整数。

例如,如果字符串中的第一个字符为“ J”,则为ASCII 0x4a或0b01001010。 因此,我将提取成对的[01,00,10,10]对,将其转换为[1、0、2、2]。

在这里,速度是我的第一要务,因此我正在寻找一种快速的方法来实现这一目标。

非常感谢您的任何帮助,谢谢。

您可以使用np.unpackbits

def bitpairs(a):
    bf = np.unpackbits(a)
    return bf[1::2] + (bf[::2]<<1)
    ### or: return bf[1::2] | (bf[::2]<<1) but doesn't seem faster

### small example
bitpairs(np.frombuffer(b'J', 'u1'))
# array([1, 0, 2, 2], dtype=uint8)

### large example
from string import ascii_letters as L
S = np.random.choice(array(list(L), 'S1'), 1000000).view('S1000000').item(0)
### one very long byte string
S[:10], S[999990:]
# (b'fhhgXJltDu', b'AQGTlpytHo')
timeit(lambda: bitpairs(np.frombuffer(S, 'u1')), number=1000)
# 8.226706639004988

您可以对字符串进行切片并假设基数为2转换为int

>>> byt = '11100100'
>>> [int(b, 2) for b in (byt[0:2], byt[2:4], byt[4:6], byt[6:8])]
[3, 2, 1, 0]

假定byt始终是8个字符的str ,而不是通过二进制文字 b11100100形成的int。

更通用的解决方案可能类似于:

>>> def get_int_slices(b: str) -> list:
...     return [int(b[i:i+2], 2) for i in range(0, len(b), 2)]
... 
>>> get_int_slices('1110010011100100111001001110010011100100')
[3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0, 3, 2, 1, 0]

int(x, 2)调用说:“将输入解释为以2为底。”


*据我所知,我的答案都没有赢得过与保罗·潘泽(Paul Panzer)的速度竞赛,这个答案也不例外。

暂无
暂无

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

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