字节到整数的转换

问题描述 投票:2回答:2

如果我使用函数int.from_bytes()转换为十六进制形式的字节,则会得到预期的ans。但是当字节为十进制形式时,我得到一个意外的值。我无法理解其背后的数学原理,请解释。我对此并不陌生,我的问题可能很愚蠢,请尝试从下面的示例代码中了解。

>>> testBytes = b'\x10'
>>> int.from_bytes(testBytes, byteorder='big', signed=True)
16
>>>testBytes1 = b'10'
>>>int.from_bytes(testBytes1, byteorder='big', signed=True)
12592

testBytes1变量中的预期答案为10,为什么我得到这么大的值,该函数如何工作,如何将testBytes1值作为整数10保留为字节形式。我正在通过USB端口接收testBytes1

python python-3.x type-conversion byte endianness
2个回答
0
投票

您可以将字节转换为字符串,然后将其转换为整数。

>>> B = b'10'
>>> int(B.decode('utf-8'))
10

2
投票

这只是简单地获取每个字符的ascii值:

代码:

testBytes1 = b'10'
print(int.from_bytes(testBytes1, byteorder='big', signed=True))

testBytes1 = b'\x31\x30'
print(int.from_bytes(testBytes1, byteorder='big', signed=True))

结果;

12592
12592
© www.soinside.com 2019 - 2024. All rights reserved.