Search code examples
pythonhexendianness

Python) Convert Big Endian to Little Endian


I have a file (.vcon) that contains hexadecimal strings (around 2,000 bytes) stored in big endian and want to convert this file to little endian hexadecimal string .vcon file based on the rule set.

Inside a list, there are four possible values : 8, 16, 32, 64 If a number in a list is 8, then no switiching (from big to little endian) is necessary since the data is one byte. Other than 8, the data must be switched from big to little endian.

I have trouble coming up with a way to go about this.

For example, if my data in the .vcon file (big endian) is as follows

F324658951425AF3EB0011

and the numbers in the list are as follows

[16, 8, 8, 32, 8, 16] 

then the resulting data we create should be as follows (to little endian)

24F36589F35A4251EB1100

How should I iterate through the numbers in a list while also accessing each byte in a hexadecimal string file (that is in big endian format) and create a new hexadecimal string file in little endian format?


Solution

  • Using a bytearray (Try it online!):

    data = "F324658951425AF3EB0011"
    bits = [16, 8, 8, 32, 8, 16]
    
    b = bytearray.fromhex(data)
    i = 0
    for n in bits:
        n //= 8
        b[i:i+n] = reversed(b[i:i+n])
        i += n
    print(b.hex().upper())
    

    Or with memoryview (Try it online!):

    data = "F324658951425AF3EB0011"
    bits = [16, 8, 8, 32, 8, 16]
    
    b = bytearray.fromhex(data)
    m = memoryview(b)
    for n in bits:
        n //= 8
        m[:n] = m[n-1::-1]
        m = m[n:]
    print(b.hex().upper())