从六进制字符串中提取单个位值的有效方法

2024-04-29 10:30:25 发布

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

我正在开发一个实时应用程序,我必须尽快处理一行数据,才能将其发送到应用程序。这些线路到达的速度非常快,大约每分钟40k。任务是从行中的hexa数据中提取某些单个位的值。我已经有了一个解决方案,但我怀疑这是最有效的,所以我想问你是否可以改进它。你知道吗

数据样本行:

p1                p2      p3     len  data
1497383697        0120    000    5    00 30 63 4f 15

len是数据中有多少字节,data是我们正在处理的。假设我想从左边的第11位开始提取3位。使用填充将十六进制转换为二进制:
0x0030634f15=0000 0000 0011 0000 0110 0011 0100 1111 0001 0101
需要的值是0b110,它是十进制的6。你知道吗

我的解决办法是:

# 11 and 3 in the example
start = config.getint(p, 'start') 
length = config.getint(p, 'length')

parts = line.split()
hexadata = ''.join(parts[4:])
bindata = bin(int(hexadata, 16))[2:].zfill(len(hexadata) * 4)
val = int(bindata[start:start + length], 2)

val最终将保持值6。还有其他更有效的方法吗?谢谢


Tags: 数据config应用程序datalenvalstartlength
1条回答
网友
1楼 · 发布于 2024-04-29 10:30:25

将输入转换为数字并使用位操作比使用字符串操作更快:

parts = line.split(maxsplit=4)

# remove spaces in the number and convert it to int from base 16
num = int(parts[4].replace(' ', ''), 16)

# create a bit mask with exactly `length` 1s
mask = (1 << length) - 1

# calculate the offset from the right
shift = 40 - start - length

# shift the value to the right and apply the binary mask to get our value
val = (num >> shift) & mask

根据我的计时,位运算快了大约20%。100万次迭代的计时结果:

string_ops  2.735653492003621 seconds
bit_ops     2.190693126998667 seconds

相关问题 更多 >