Search code examples
pythoncstructbuffer

Convert buffer repesents list of int little indian Python class


I'm trying to get data from buffer represents as string,

Example:

got :

str = "0004000001000000020000000A000000"


class MyData:
    length
    some_data
    array_data
    buf_data

data = parse(str)

Except :

length=1024, some_data=1, array_data=[2,10], buf_data="000000020000010"

Explain:

length=1024 since the 8 numbers "00040000" repesnts an hex number in little indian

and the rest the same idea, "00040000 01000000 0200000 00A000000"

1024, 1, 2, 10

any idea?

I have some solution but it's too messy and isn't easy to support


Solution

  • This is one way to do it:

    class MyData:
        mmap = [16**1, 16**0, 16**3, 16**2, 16**5, 16**4, 16**7, 16**6]
        def __init__(self, buffer):
            self.buffer = buffer
            self.integers = []
        def get_integers(self):
            if len(self.integers) == 0:
                for i in range(0, len(self.buffer), 8):
                    a = 0
                    for x, y in zip(self.buffer[i:i+8], self.mmap):
                        a += int(x, 16) * y
                    self.integers.append(a)
            return self.integers
    
    mydata = MyData('0004000001000000020000000A000000')
    
    print(mydata.get_integers())
    

    Output:

    [1024, 1, 2, 10]
    

    NOTE: This is specifically for 32-bit unsigned values