Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting string to raw bytes

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
like image 572
StepTNT Avatar asked Dec 06 '22 08:12

StepTNT


2 Answers

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.

like image 147
Martijn Pieters Avatar answered Dec 08 '22 20:12

Martijn Pieters


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))
like image 27
Ronald Paul Avatar answered Dec 08 '22 20:12

Ronald Paul