Converting string to raw bytes

arrays, byte, python, string

Solution

Use `binascii.unhexlify()`:

import binascii

binary = binascii.unhexlify(text)

The same module has `binascii.hexlify()` too, to mirror the operation.

Demo:

>>> import binascii
>>> binary = '\x5A\x05\x70\x5D\xC2\x5C\xA1\x51\x23\xC8\xE4\x75\x0B\x80\xD0\xA9'
>>> text = '5A05705DC25CA15123C8E4750B80D0A9'
>>> binary == binascii.unhexlify(text)
True
>>> text == binascii.hexlify(binary).upper()
True

The `hexlify()` operation produces lowercase hex, but that is easily fixed with a `.upper()` call.

Problem

I wrote a program that works with raw bytes (I don't know if this is the right name!) but the user will input the data as plain strings. How to convert them? I've tried wih a method but it returns a string with length 0! Here's the starting string: ``` 5A05705DC25CA15123C8E4750B80D0A9 ``` Here's the result that I need: ``` \x5A\x05\x70\x5D\xC2\x5C\xA1\x51\x23\xC8\xE4\x75\x0B\x80\xD0\xA9 ``` And here's the method I wrote: ``` def convertStringToByte(string): byte_char = "\\x" n=2 result = "" bytesList = [string[i:i+n] for i in range(0, len(string), n)] for i in range(0, len(bytesList)): bytesList[i] = byte_char + bytesList[i] return result ```

Original source