Search code examples
pythonhexendianness

Convert hex to uint16 little-endian


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.


Solution

  • 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)