JeanP
JeanP

Reputation: 507

Print Decimal value from long string of little endian hex values

I am trying to read few lines of hex values from a long string of hexadecimal values then convert them into little endian and then convert that into decimal.

Here's an example of what I am trying to do:

LittleEndian Example

From Step 1 to Step 2 I have the follow lines of code that will execute the that step:

""" Convert to Hexadecimal """
    def dump(s):
        import types
        if type(s) == types.StringType:
            return dumpString(s)
        elif type(s) == types.UnicodeType:
            return dumpUnicodeString(s)

    FILTER = ''.join([(len(repr(chr(x))) == 3) and chr(x) or '.' for x in range(256)])

    def dumpString(src, length=16):
        result = []
        for i in xrange(0, len(src), length):
           chars = src[i:i+length]
           hex = ' '.join(["%02x" % ord(x) for x in chars])
           printable = ''.join(["%s" % ((ord(x) <= 127 and FILTER[ord(x)]) or '.') for x in chars])
           result.append(hex)
        return ''.join(result)

""" _____________________________________________ """

    t = dump(TEST.encode("utf8", "replace")) #TEST is a string of characters

This is more or less what I have for the first jump from Step 1 to Step 2. Now from Step 2 to Step 3 I was trying something along of the lines of:

newString = t[54:59]

However I'm unsure if the following method will work correctly when using different length of strings. It might work for the current string. So now that I have the bytes I want to focus on I am unsure of how to convert these bits into little endian in order to convert that then into decimal. Does Python have built in libraries that can aid me in converting? or using maybe a string modifier?

Upvotes: 0

Views: 1257

Answers (1)

ohe
ohe

Reputation: 3683

To convert a string representing hexadecimal bites from big-endian to little endian, you can do the following:

hex_string = hex(struct.unpack('<I', struct.pack('>I', int(val, 16)))[0])

where val is your string (here: 9a04). The returned value will be an hex string. You can convert it with:

hex_string = hex_string[2:].zfill(8)[:4]

Upvotes: 1

Related Questions