[英]Why does to_bytes(2, byteorder="big") return sometimes only one byte?
I really don't understand why does sometimes to_bytes return not what I want.我真的不明白为什么有时 to_bytes 返回的不是我想要的。 For instance, here is an expected behavior:
例如,这是一个预期的行为:
i = 12
i.to_bytes(2, byteorder="big")
>> b'\x00\x0c'
However, here is sometimes the output:然而,这里有时是 output:
i = 870
i.to_bytes(2, byteorder="big")
>> b'\x03f'
while I would like to have:而我想要:
>> b'\x03\x66'
Does anyone have any clue?有没有人有任何线索? Is there another way to obtain what I want?
还有其他方法可以得到我想要的吗? Thanks a lot !
非常感谢 !
I tried other method with format, hex, ... but I really want bytes in hexadecimal format with '\x'...我尝试了其他格式、十六进制的方法,...但我真的想要带有 '\x' 的十六进制格式的字节...
The method to_bytes()
(in your case) produces a byte array of length 2. It renders however python wants to render it. to_bytes()
方法(在您的情况下)生成一个长度为 2 的字节数组。它呈现 python 想要呈现它。
If you want it printed differently, you can convert it to a string like this:如果你想以不同的方式打印它,你可以将它转换成这样的字符串:
i = 12
byts = i.to_bytes(2, byteorder="big")
out = ''.join(f'\\x{b:02x}' for b in byts)
print(out)
Output: Output:
\x03\x66
Note that the output is a string and not a byte array.请注意,output 是一个字符串而不是字节数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.