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?

4
  • 1
    @downvoter: It's a valid question, why the downvote? Commented Sep 13, 2017 at 7:30
  • 2
    I did't down vote :), May be because of lack of research to ask this question. Commented Sep 13, 2017 at 7:32
  • 1
    It is not a duplicate of that question, because he has leading '0x' Commented Sep 13, 2017 at 7:35
  • true i have this extra 0x which i am trying to convert to bytes, i tried doing a int conversion and then to bytes, but the solution from @koalo is perfect, marking it as best answer Commented Sep 15, 2017 at 12:01

1 Answer 1

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]    
Sign up to request clarification or add additional context in comments.

1 Comment

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 :(

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.