I need help on converting HEX string to int. I have a big data input, but, Here's one example from the data:
def convert_hex_to_int(n:int, interval:int):
splitted = [hex(n)[2:][i:i + interval] for i in range(0, len(hex(n)[2:]), interval)]
return [float(int(hex(unpack('<H', pack('>H', int(i, 16)))[0]), 16)) for i in splitted]
a='0x0E070907'
hex_int = int(a, 16)
result_print = (convert_hex_to_int(hex_int, 4))
and instead of
[1806.0, 1801.0]
the result is
[28896.0, 1801.0]
the function convert_hex_to_int is to split the string into 2 bytes and swap it, with the interval of 4 bytes. And the purpose of the code it to acquire the floating points of the HEX String. I suspected it has to do the Python removing the first zero on the front of 070E, and instead, it becomes 70E0.
You can use the fromhex classmethod of the bytes builtin to convert the hex to bytes, then unpack them however you please:
>>> a='0x0E070907'
>>> h = bytes.fromhex(a[2:])
>>> h
b'\x0e\x07\t\x07'
>>> struct.unpack('<2H', h)
(1806, 1801)
If you don't know the number of bytes in advance you can generate a format string to match your data.
>>> a='0x9406920691068F06'
>>> bs = bytes.fromhex(a[2:])
>>> bs
b'\x94\x06\x92\x06\x91\x06\x8f\x06'
>>> len(bs)
8
>>> # Each 'H' is 2 bytes, multiply 'H' by half
>>> # the number of bytes to gt the format string.
>>> fmt = '<' + ('H' * (len(bs)//2))
>>> struct.unpack(fmt, bs)
(1684, 1682, 1681, 1679)
This will only work if the number of bytes to be unpacked is evenly divisible by the number of bytes in the target data type. If this is not the case - for example if you're reading a stream from a socket - then you'll have to accumulate data until you have a suitable quantity.