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? Specifically, for int value of 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. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.