1

i have hex list like this ['0x1', '0x3', '0x2', '0x0', '0x0', '0x10', '0x4', '0x0', '0x0', '0xfa', '0x4']

and i intend to send it over USB, so i need to convert into a bytearray, is there a way available in python?

Sandeep Shyam
  • 123
  • 3
  • 10

1 Answers1

5

That can be solved by a simple one line expression

input = ['0x1', '0x3', '0x2', '0x0', '0x0', '0x10', '0x4', '0x0', '0x0', '0xfa', '0x4']
result = bytes([int(x,0) for x in input])

The result is

b'\x01\x03\x02\x00\x00\x10\x04\x00\x00\xfa\x04'

If you do not actually want to have a byte array, but an array of integers, just remove the bytes()

result = [int(x,0) for x in input]

The result is

[1, 3, 2, 0, 0, 16, 4, 0, 0, 250, 4]    
koalo
  • 2,113
  • 20
  • 31
  • thanks @koalo for your response, one small correction is to use bytearray instead of bytes , i am not sure if its due to my version of python (i am using 2.7), using bytes gives me int array somehow :( – Sandeep Shyam Sep 15 '17 at 12:40