简体   繁体   English

python将整数打包为十六进制字节

[英]python pack integer as hex byte

I thought this would be simple, but spent quite some time trying to figure it out. 我以为这很简单,但是花了很多时间试图弄清楚。

I want to convert an integer into a byte string, and display in hex format . 我想将整数转换为字节字符串,并以十六进制格式显示。 But I seem to get the ascii representation? 但是我似乎得到了ascii表示形式? Specifically, for int value of 122 . 具体来说,int值为122

from struct import *
pack("B",122) #this returns b'z', what i need is 'b\x7A'
pack("B",255) #this returns b'\xff', which is fine.

I know in python 2.x you can use something like chr() but not in python 3, which is what I have. 我知道在python 2.x中可以使用类似chr()但是在python 3中则不能,这就是我所拥有的。 Ideally the solution would work in both. 理想情况下,该解决方案在两种情况下均适用。

You can use codecs or string encoding 您可以使用编解码器或字符串编码

codecs.encode(pack("B",122),"hex")

or 要么

a = pack("B",122)
a.encode("hex")

I think you are getting the results you desire, and that whatever you are using to look at your results is causing the confusion. 我认为您正在获得想要的结果,并且无论您使用什么来查看结果,都会造成混乱。 Try running this code: 尝试运行以下代码:

from struct import *
x = pack("B",122)
assert 123 == x[0] + 1

You will discover that it works as expected and does not assert. 您会发现它可以按预期运行并且不会断言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM