1

I have a string of bytes like this:

mystring = '000102'

And I need:

result = b'\x00\x01\x02'

Now I did:

# Opt 1
result = bytearray(mystring, 'utf-8') # I suppose is not correct encoded
# Opt 2
result  = mystring.encode()

And both give me, b'000102'. How can I obtain the '\x' that defines every byte?

Thank you very much, I suposes is an easy question, but I can't find how do it

Lleims
  • 1,275
  • 12
  • 39
  • 1
    [Python 3 - Hex-String to bytes - Stack Overflow](https://stackoverflow.com/questions/47996767/python-3-hex-string-to-bytes) ? – user202729 Feb 12 '21 at 12:40
  • Does this answer your question? [How to create python bytes object from long hex string?](https://stackoverflow.com/questions/443967/how-to-create-python-bytes-object-from-long-hex-string) – user202729 Feb 12 '21 at 12:41

2 Answers2

2

use bytes fromhex method

mystring = '000102'
y = bytes.fromhex(mystring)
print(y)

output:

b'\x00\x01\x02'
kiranr
  • 2,087
  • 14
  • 32
0

This should do it:

my_string = "012345"

result = b""

for i in range(len(my_string)//2):
    b += bytes(chr(int(my_string[i:i+1],16)),encoding="ASCII")
Minek Po1
  • 142
  • 1
  • 9