2

What is the easiest way of converting a ASCII-String into hex without changing the value?

what i have:

string = "00FA0086"

what i want:

hex_string = b'\x00\xFA\x00\x86"

Is there a simple way or do i need to write a function?

tryanderror
  • 153
  • 1
  • 9
  • 1
    What have you tried so far? Can you show a [mcve]? – Arya McCarthy Feb 21 '20 at 14:07
  • The first thing i tried till now is the decode function with this: `decode(string, 'hex_codec')` but this will give me not the same value it will just look up what as example "FA" has as hex-value. I was just looking for a build-in function in python to get me "what i want". If there arent any, i'm going to write something, but i would recommend to have a clean built-in function – tryanderror Feb 21 '20 at 14:12

1 Answers1

5

You are looking for the binascii module from the Standard Python Library:

import binascii

string = "00FA0086"

print(repr(binascii.a2b_hex(string)))

gives:

b'\x00\xfa\x00\x86'
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
  • Yeah, thank u very much! This was what i was looking for – tryanderror Feb 21 '20 at 14:20
  • when i want to convert a bigger string like ''00009e0890423374'' i get something like b'\x00\x00\x9e\x08\x90B3t'. Is there a other function for longer strings like this one? – tryanderror Feb 21 '20 at 14:31
  • @tryanderror: 0x42 is ascii code for `B`, 0x33 for `3` and 0x74 for `t`, hence the result. The representation of a byte representing an ascii character is that character. – Serge Ballesta Feb 21 '20 at 14:40