整数转字节 – 转换问题 – Python

huangapple go评论53阅读模式
英文:

integer to bytes - conversion problems - Python

问题

我想通过串行总线向设备发送数据。需要将整数值转换为4个字节。到目前为止一切都好。

对于大多数值,它都有效,但例如对于100,我得到了我不理解的结果:

(5000).to_bytes(4, byteorder='big') -> b'\x00\x00\x13\x88'

这是我从纸上预期的,然而

(100).to_bytes(4, byteorder='big') -> b'\x00\x00\x00d'

而我期望的是对于100,4个字节为b'\x00\x00\x00\x64'

为什么会有差异?

如何将长度修正为确切的4字节表示?

英文:

I want to send data via a serial bus to a device. Need to convert integer values to 4 bytes. So far so good.

For most values it works, while for e.g. 100 I get results which I do not understand:

(5000).to_bytes(4, byteorder='big') -> b'\x00\x00\x13\x88'

that's what I expected from paper, however

(100).to_bytes(4, byteorder='big') -> b'\x00\x00\x00d'

while I would expect for 100 the 4 bytes b'\x00\x00\x00\x64'

Why the difference?

How to fix the length to -exactly- a 4 byte representation?

答案1

得分: 2

在Python中,字节字符串中的 dP 值是表示ASCII字符的字节,其中 d 替换为 64,而 P 替换为 50。这是Python的工作方式,我想是这样。

现在,让我们看一个示例:

int.from_bytes(b'\x00\x00\x00d', byteorder='big')
#输出
100

int.from_bytes(b'\x00\x00\x00\x64', byteorder='big')
#输出
100

您也可以使用 bytes.hex() 进行检查:

b'\x00\x00\x00\x64'.hex()
#输出
'00000064'

b'\x00\x00\x00d'.hex()
#输出
'00000064'
英文:

In python, the d and P values in bytestrings are bytes that represent ASCII characters, where the d replaces 64 and P replaces 50. This is the way python does I guess.

Now, let us see with example:

int.from_bytes(b'\x00\x00\x00d', byteorder='big')
#output
100

int.from_bytes(b'\x00\x00\x00\x64', byteorder='big')
#output
100

You can also check with bytes.hex()

b'\x00\x00\x00\x64'.hex()
#output
'00000064'


b'\x00\x00\x00d'.hex()
#output
'00000064'

huangapple
  • 本文由 发表于 2023年3月15日 18:41:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75743580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定