Jim
Jim

Reputation: 875

convert hexstring to individual bytes python 2.7

Morning all,

This is probably super easy but my brain just isn't working today.

So I have a string of hex f70307d600017010 I need to convert it to \xf7\x03\x07\xd6\x00\x01\x70\x10

or something to that effect, i.e escaping the string to hex.

Anyone have any suggestions?

Thanks Jim

Upvotes: 0

Views: 595

Answers (3)

Alfe
Alfe

Reputation: 59436

There are several solutions to this using regular expressions. My favorite is this:

re.sub('(..)', r'\x\1', 'f70307d600017010')

Another could be:

''.join(r'\x' + x for x in re.findall('..', 'f70307d600017010'))

These will create a string of escaped bytes (based on the assumption that the tag "escaping" was meaning this). If you instead want to create a string of unescaped bytes:

re.sub('(..)', lambda m: chr(int(m.group(), 16)), 'f70307d600017010')

EDIT: I now prefer the answer of @juanpa-arrivillaga using the binascii module: binascii.unhexlify('f70307d600017010')

Upvotes: 0

juanpa.arrivillaga
juanpa.arrivillaga

Reputation: 95957

If you want the result of that output as a literal, i.e.:

>>> '\xf7\x03\x07\xd6\x00\x01\x70\x10'
'\xf7\x03\x07\xd6\x00\x01p\x10'

Use the binascii module:

>>> import binascii
>>> s = "f70307d600017010"
>>> binascii.unhexlify(s)
'\xf7\x03\x07\xd6\x00\x01p\x10'

Upvotes: 2

Jack Nicholson
Jack Nicholson

Reputation: 205

This is by no means the way you should be doing it, but considering I'm bored:

x = "f70307d600017010"
y = "\\"
count = 1
for letter in x:
    print(count)
    if count > 2:
        y = y + "\\" + "x" + letter
        count = 1
    elif 1 == count:
        y = y + "x" + letter
    elif count % 2 == 1:
        y = y + letter + "\\"
    elif count % 2 == 0:
        y = y + letter

    count = count + 1

Upvotes: 1

Related Questions