Home > Software engineering >  Python 3.8: Bytes to a list of hex
Python 3.8: Bytes to a list of hex

Time:09-28

I'm currently banging by head bloody over this problem I have:

I have a method where I receive a byte input of a defined length of 8:

def ConvertToHexAndSend(serialnumber):
   if len(serialnumber) != 8:
      throw a good exception...
   Some good converter code here..

The method shall then take the serialnumber and split it into a list with the size 4.

Example:

serialnumber = b'12345678'

Expected output:

[0x12, 0x34, 0x56, 0x78]

What I have tried so far:

new_list = list(serialnumber) # Gives a list of [49, 50, 51, 52, 53, 54, 55, 56] and then:
first byte = new_list[0] << 8   new_list[1] # gives some riddish value 

and

hex(serialnumber[0]) # Gives '0x32' string

and

first_byte = serialnumber[0]   serialnumber[1] # Gives int 99

But no success so far.. any idea?

CodePudding user response:

You want something like:

result = list(bytes.fromhex(serialnumber.decode('ascii')))

Your bytes are represent a hex-string. So use the bytes.fromhex to read that (converting the bytes to str first), and you can use list to get a list of int objects from the new resulting bytes object

  • Related