Reputation: 10041
I need to convert an integer into a series of byte strings, and it looks like struct.pack
is the best way to do that. One line gets me all the information I need:
In [51]: struct.pack("@L",1000)
Out[51]: '\xe8\x03\x00\x00'
My issue is that I ultimately want to convert those to a list of strings (I'm passing them through a CAN utility that requires the bytes to be taken as strings... ultimately I'll bypass the utility, but this is where I'm at for now)
So I try to access the string, but it's a different sort of string...
In [52]: output=struct.pack("@L",1000)
In [53]: type(output)
Out[53]: str
In [54]: output[0]
Out[54]: '\xe8'
In [55]: type(output[0])
Out[55]: str
In [56]: output[0][0]
Out[56]: '\xe8'
So not quite sure where to go from here. Ultimately, I want to end up with something like
(0xe8, 0x03,0x00,0x00)
Upvotes: 3
Views: 211
Reputation: 67063
It sounds like you want a list of the byte values as integers. Here's what you can do:
>>> import struct
>>> x = struct.pack("@L",1000)
>>> map(ord, x)
[232, 3, 0, 0]
If you really want hex strings:
>>> map(hex, map(ord, x))
['0xe8', '0x3', '0x0', '0x0']
Upvotes: 1