Sean McCarthy
Sean McCarthy

Reputation: 5558

Convert binary <something> of hex bytes to list of decimal values

I have the following binary (something):

test = b'40000000111E0C09'

Every two digits is a hexadecimal number I want out, so the following is clearer than the above:

test = b'40 00 00 00 11 1E 0C 09'

0x40 = 64 in decimal
0x00 = 0 in decimal
0x11 = 17 in decimal
0x1E = 30 in decimal

You get the idea.

How can I use struct.unpack(fmt, binary) to get the values out? I ask about struct.unpack() because it gets more complicated... I have a little-endian 4-byte integer in there... The last four bytes were:

b'11 1E 0C 09'

What is the above in decimal, assuming it's little-endian?

Thanks a lot! This is actually from a CAN bus, which I'm accessing as a serial port (frustrating stuff..)

Upvotes: 0

Views: 308

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195428

Assuming you have string b'40000000111E0C09', you can use codecs.decode() with hex parameter to decode it to bytes form:

import struct
from codecs import decode
test = b'40000000111E0C09'
test_decoded = decode(test, 'hex') # from hex string to bytes

for i in test_decoded:
    print('{:#04x} {}'.format(i, i))

Prints:

0x40 64
0x00 0
0x00 0
0x00 0
0x11 17
0x1e 30
0x0c 12
0x09 9

To get last four bytes as UINT32 (little-endian), you can do then (struct docs)

print( struct.unpack('<I', test_decoded[-4:]) )

Prints:

(151789073,)

Upvotes: 1

Related Questions