1

I'm trying to convert a list of hexadecimal strings into little-endian format.

Code:

hex = ['1A05','1A05','1A05'] 
endian = int(str(hex),16)
print(endian)

However, it doesn't work and throws an error:

ValueError: invalid literal for int() with base 16:

I was expecting:

[1306, 1306, 1306]

Interestingly if I write:

endian = int('1A05',16)

I don't get an error and it returns

6661

But this is the result of interpreting '1A05' as big-endian. I was expecting to get 1306 (0x051A) as result.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
red_sach
  • 47
  • 1
  • 8
  • You get the first error, because you are trying to convert the string representation of a list to an integer. – mkrieger1 Jun 22 '20 at 19:35
  • @mkrieger1 I think what he means is that it's the result of treating the hex bytes as big-endian, he wants `1A05` to be parsed as `051A` – Barmar Jun 22 '20 at 19:39
  • @Barmar Yes I got it now. I'm sure this has been asked before, but I didn't find a good duplicate yet. – mkrieger1 Jun 22 '20 at 19:41
  • The proper way would consist of two steps: (1) parse hex string into `bytes` ([duplicate #1](https://stackoverflow.com/questions/5649407/hexadecimal-string-to-byte-array-in-python)); (2) convert `bytes` to integer, specifying little-endian byte order ([duplicate #2](https://stackoverflow.com/questions/34009653/convert-bytes-to-int)). – mkrieger1 Jun 22 '20 at 19:47
  • You have two problems as @mkrieger1 pointed out. Solve both using the links he provided. – Braiam Jun 22 '20 at 19:53

1 Answers1

1

You need to process each element of the list separately, not the whole list at once. You can do this with a list comprehension.

If you want little-endian, you have to swap the halves of the string before parsing it as an integer:

hex = ['1A05','1A05','1A05'] 
endian = [int(h[2:4] + h[0:2], 16) for h in hex]

However, that will only work if the hex strings are always 4 characters. You can also swap the bytes of the integer using bit operations after parsing:

for h in hex:
    i = int(h, 16)
    i = i & 0xff << 16 | i & 0xff00 >> 16
    endian.append(i)
Barmar
  • 741,623
  • 53
  • 500
  • 612