I’d like to convert an array of integer values I have received over USB using pyusb to a list of hex values. I’d like these hex values to always have two bytes, i.e. 0x##. However the normal hex() function will return 0x1 with an input of 1. I’d like it to return 0x01.
Then after having the list of hex values I’d like to append them together while throwing away the ‘0x’ portion. This is what I currently have, pretty simple.
data_read = dev.read(0x82,64,0,1000)
hex_data = range(0,len(data_read))
for i in range(0,len(data_read)):
hex_data[i] = hex(data_read[i])
Any ideas? I can fudge it and do it the sloppy way, but I was hoping there is a proper way to do it. Thank you.
Update:
data_read = dev.read(0x82,64)
print data_read
>>> array('B', [169, 86, 128, 1, 0, 128])
for i in range(0,len(data_read)):
hex_data[i] = hex(data_read[i])
print hex_data
>>> ['0xa9', '0x56', '0x80', '0x1', '0x0', '0x80']
The method suggested by Lavon did not work since the resulting hex values were technically strings in my code? Instead I just skipped my whole for loop converting to hex and directly did as Lavon and moooeeeep suggested and it worked! Thanks!
hex_data = ('%02x' %i for i in data_read)
print ''.join(hex_data)
>>> a95680010080
Is there a good reference you use for syntax? i.e. the ‘%02x’ you used? I haven’t seen that before and would like to understand it better.
Does this fit the bill?
yields:
using list comprehension and the join operation.
Alternatively, as suggested by @moooeeeep here is the solution using a generator:
For the string formatting options, see this