0

I have a list of hex numbers:

[0xaa4d, 0x4643, 0x3353, 0x074c, 0x4854, 0x4138]

My goal is to convert it to something like this:

aa4d46433353074c48544138

What I've tried:

list = [0xaa4d, 0x4643, 0x3353, 0x074c, 0x4854, 0x4138]
string = ''.join('%02x' % i for i in list)

The output is:

aa4d4643335374c48544138

So, it's seems like OK, but, as we see, the output is somehow different from what I need, because 0x074c converts to 74c instead of 074c

I've also tried this:

l = [0xaa4d, 0x4643, 0x3353, 0x074c, 0x4854, 0x4138]

s = ''.join('{:02x}'.format(i) for i in l)

print(s)

This still gives me wrong results. I've also tried different numbers at '{:02x}' & '%02x', but still no luck.

My thoughts that converting hex to string removes leading zeros, but I don't know how to do it right.

My question is how to convert 0x074c to 074c without losing leading zero. Cause my code gives me 74c instead. What am I missing here?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • `"".join(f"{i:04x}" for i in hexlist)` will do the trick. You need the `04` in the formatting sequence to guarantee you get all 4 bytes of each hex digit. – MattDMo May 19 '22 at 20:01
  • @MattDMo your suggestion is correct! I've got this string: `aa4d46433353074c48544138` Could you please explain the meaning of `f` right after join? I've tried `'{:02x}'` and it wasn't any helpful. – Lethaquell May 19 '22 at 20:05
  • The `f` means the following string is a formatted string or f-string. They were introduced in Python 3.6. You can read all about them in the docs [here](https://docs.python.org/3/tutorial/inputoutput.html#formatted-string-literals) and [here](https://docs.python.org/3/reference/lexical_analysis.html#f-strings). – MattDMo May 19 '22 at 20:08
  • @MattDMo got you. If it possible, could you please explain how to do the same on Python 2.7. Cause unfortunately my project is currently on 2.7 ver. – Lethaquell May 19 '22 at 20:11
  • `".join("%04x" % i for i in hexlist)` should do it. `"".join("{:04x}".format(i) for i in hexlist)` will also work, depending on whether you want to use old- or new-style formatting. – MattDMo May 19 '22 at 20:17

0 Answers0