简体   繁体   English

为什么 to_bytes(2, byteorder="big") 有时只返回一个字节?

[英]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.

相关问题 为什么`(33).to_bytes(2,'big')`返回'b'\\ x00!'`而不是'b'\\ x00 \\ x21'`? - Why does `(33).to_bytes(2, 'big')` return `b'\x00!'` instead of `b'\x00\x21'`? Python 返回的 to_bytes 不符合预期 - Python return for to_bytes not as expected 将 integer 转换为半字节,`to_bytes()`? - Convert integer to half-byte, `to_bytes()`? Python 如何将 int 转换为字节 Little Endian (.to_bytes(4, 'little')) - python 到 javascript(nodejs) - How does Python convert and calculate an int to byte Little Endian (.to_bytes(4, 'little')) - python to javascript(nodejs) Python:为什么peek(1)返回8K字节而不是1字节? - Python: why does peek(1) return 8K bytes instead of 1 byte? 为什么Python中的bytearray函数将一个字节变成两个字节? - Why does bytearray function in Python turn one byte into two bytes? Clojure等效于python int.from_bytes(byteorder ='big') - Clojure equivalent of python int.from_bytes(byteorder='big') 为什么Python 3.6.4从to_bytes()方法返回意外字符? - Why Python 3.6.4 returns unexpected characters from to_bytes() method? 为什么这段代码返回一个答案,但有时返回两个? - Why does this snippet of code return one answer but sometimes two? 为什么 max() 有时会返回 nan 有时会忽略它? - Why does max() sometimes return nan and sometimes ignores it?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM