在 Python 3 中将 int 转换为字节 [英] Converting int to bytes in Python 3
问题描述
我试图在 Python 3 中构建这个字节对象:
b'3\r\n'
所以我尝试了显而易见的(对我来说),并发现了一个奇怪的行为:
<预><代码>>>>字节(3)+ b'\r\n'b'\x00\x00\x00\r\n'显然:
<预><代码>>>>字节(10)b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'我一直无法看到有关为什么字节转换以这种方式工作的任何指针阅读文档.但是,我确实在这个 Python 问题中发现了一些关于将 format
添加到字节的令人惊讶的消息(另请参阅 Python 3 bytes格式):
http://bugs.python.org/issue3982
<块引用>这与像 bytes(int) 现在返回零这样的奇怪现象的交互更差
和:
<块引用>如果 bytes(int) 返回那个 int 的 ASCII 化,对我来说会方便得多;但老实说,即使是错误也会比这种行为更好.(如果我想要这种行为 - 我从来没有 - 我宁愿它是一个类方法,像bytes.zeroes(n)"一样调用.)
有人可以解释我这种行为的来源吗?
这就是它的设计方式 - 这是有道理的,因为通常,您会在可迭代对象而不是单个整数上调用 bytes
:
文档说明了这一点,以及字节的文档字符串代码>:
<代码> >>>帮助(字节)...字节(整数)->由用空字节初始化的参数给出的大小的字节对象
I was trying to build this bytes object in Python 3:
b'3\r\n'
so I tried the obvious (for me), and found a weird behaviour:
>>> bytes(3) + b'\r\n'
b'\x00\x00\x00\r\n'
Apparently:
>>> bytes(10)
b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
I've been unable to see any pointers on why the bytes conversion works this way reading the documentation. However, I did find some surprise messages in this Python issue about adding format
to bytes (see also Python 3 bytes formatting):
http://bugs.python.org/issue3982
This interacts even more poorly with oddities like bytes(int) returning zeroes now
and:
It would be much more convenient for me if bytes(int) returned the ASCIIfication of that int; but honestly, even an error would be better than this behavior. (If I wanted this behavior - which I never have - I'd rather it be a classmethod, invoked like "bytes.zeroes(n)".)
Can someone explain me where this behaviour comes from?
That's the way it was designed - and it makes sense because usually, you would call bytes
on an iterable instead of a single integer:
>>> bytes([3])
b'\x03'
The docs state this, as well as the docstring for bytes
:
>>> help(bytes)
...
bytes(int) -> bytes object of size given by the parameter initialized with null bytes
这篇关于在 Python 3 中将 int 转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!