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:

  • leading zeros should not be stripped so hex(int(data,2)) doesn't work for me
  • if len(data) %8 != 0 the string should be appended with zeros to end with a full byte

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.

其他提示

0-pad your input to a multiple of 8, then turn it into a hex value:

multiple, remainder = divmod(len(data), 8)
if remainder:
    data = format(data, '<0{}'.format((multiple + 1) * 8))
result = format(int(data, 2), '0{}x'.format((multiple + 1) * 2))

The output is padded as well to give 2 hex characters per full byte.

This gives:

>>> data = "00000111010110101"
>>> multiple, remainder = divmod(len(data), 8)
>>> if remainder:
...     data = format(data, '<0{}'.format((multiple + 1) * 8))
... 
>>> format(int(data, 2), '0{}x'.format((multiple + 1) * 2))
'075a80'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top