Python 有没有比int(byte#u buffer.encode(';hex';)更好的方法,16)

Python 有没有比int(byte#u buffer.encode(';hex';)更好的方法,16),python,integer,types,byte,Python,Integer,Types,Byte,在Python中,我经常使用以下序列从字节缓冲区获取整数值(在Python中,这是一个str) 我正在从struct.unpack()例程获取缓冲区。当我使用 byte_buffer, = struct.unpack('c', raw_buffer) int_value = int( byte_buffer.encode('hex'), 16 ) 有更好的办法吗 该模块擅长解压二进制数据 int_value = struct.unpack('>I', byte_buffer)[0] 限

在Python中,我经常使用以下序列从字节缓冲区获取整数值(在Python中,这是一个str)

我正在从struct.unpack()例程获取缓冲区。当我使用

byte_buffer, = struct.unpack('c', raw_buffer)
int_value = int( byte_buffer.encode('hex'), 16 )
有更好的办法吗

该模块擅长解压二进制数据

int_value = struct.unpack('>I', byte_buffer)[0]
限制为1字节–Noah Campbell 18分钟前

最好的方法是实例化一个结构解包

from struct import Struct

unpacker = Struct("b")
unpacker.unpack("z")[0]
请注意,如果需要无符号字节,可以将“b”更改为“b”。此外,不需要endian格式


对于任何想知道无界整数的方法的人,创建一个问题,并在注释中告诉我。

如果我们讨论的是获取字节的整数值,那么您需要:

ord(byte_buffer)

无法理解为什么还没有建议。

Noah没有指定数字将始终从0到无符号整数。@nosklo,没有,他粘贴的代码接受无界整数。尝试int(((“a”*500)。encode('hex'),16)作为证明。您能告诉我们为什么需要字节缓冲区作为python整数吗?我通常从二进制数据包流中提取值。整数值是有界的还是无界的?啊……使用b vs.b返回整数。(翻到python文档,意识到他需要继续阅读…)可能是因为struct更可能是解决他问题的其他部分的正确答案,如果从字节流中读取不同的数据段。我本来打算提出这个建议,但询问者没有说明它是有符号的还是无符号的,所以struct是最好的选择。