I need to turn a string like data = "00000111010110101"
into a hex string, in this example I need '075A80'
You may notice a few caveats:
After searching this forum and hacking together different answers, this is one way I found to do it, but it seems rather complex and I hope someone else sees a much simpler way.
data_hex = "".join([ "%02X" % int("".join(a),2) for a in izip_longest(*(iter(data),)*8, fillvalue='0')])
Thanks!
Edit: Some background on the data. The underlying data is purely bits, it does not represent an integer or other numeric value, so the leading zeros are relevant and must be represented in the result. Also appending zeros at the (right) end doesn't change the "value" in my use case.
Here is one option:
>>> data = "00000111010110101"
>>> new_data = data + '0' * ((8 - len(data)) % 8)
>>> '{0:0{width}x}'.format(int(new_data, 2), width=len(new_data) / 4)
'075a80'
The first line appends zeros so the length is a multiple of 8, and the second formats your hex string.