0

I have to take a hex string and convert it.

ex. I get this string 1101222233334444555500206666666677777777889900200012ff1f4412ff1f3720030057010000.

I have to split it up to this 11 01 22 22 33 33 44 44 55 55 00 20 66 66 66 66 77 77 77 77 88 99 00 20 00 12 ff 1f 44 12 ff 1f 37 20 03 00 57 01 00 00 and convert it.

Edit: It is from hex to decimal.

martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

2

There are a few lesser known methods of bytes objects:

>>> s='1101222233334444555500206666666677777777889900200012ff1f4412ff1f3720030057010000'
>>> bytes.fromhex(s)  # gives a byte string
b'\x11\x01""33DDUU\x00 ffffwwww\x88\x99\x00 \x00\x12\xff\x1fD\x12\xff\x1f7 \x03\x00W\x01\x00\x00'

As bytes you can get the individual values of each byte, or convert the whole thing to a list:

>>> b=bytes.fromhex(s)
>>> b[0]
17
>>> b[1]
1
>>> list(b)
[17, 1, 34, 34, 51, 51, 68, 68, 85, 85, 0, 32, 102, 102, 102, 102, 119, 119, 119, 119, 136, 153, 0, 32, 0, 18, 255, 31, 68, 18, 255, 31, 55, 32, 3, 0, 87, 1, 0, 0]

And can convert back:

>>> b.hex()  # converts back to a hex string
'1101222233334444555500206666666677777777889900200012ff1f4412ff1f3720030057010000'
>>> b.hex(sep=' ')  # adds a separator
'11 01 22 22 33 33 44 44 55 55 00 20 66 66 66 66 77 77 77 77 88 99 00 20 00 12 ff 1f 44 12 ff 1f 37 20 03 00 57 01 00 00'
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251