Converting string to raw bytes

15,846

Solution 1

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.

Solution 2

You must get from 5A (a string representing an hexidecimal number) to 0x5A or 90 (integers) and feed them into chr(). You can do the first conversion with int('0x5A', 16), so you'll get something like

chr(int('0x5A', 16))
Share:
15,846
StepTNT
Author by

StepTNT

(your about me is currently blank)

Updated on June 09, 2022

Comments

  • StepTNT
    StepTNT almost 2 years

    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