Unzip the hexadecimal string

I have a string containing the float value in hexadecimal characters, for example:

"\\64\\2e\\9b\\38"

I want to extract a float, but for this I have to make Python see the string as 4 hexadecimal characters instead of 16 regular characters. At first I tried replacing slashes, but I got an error:

>>>> hexstring.replace("\\", "\x")
ValueError: invalid \x escape

I discovered

struct.unpack("f", "\x64\x2e\x9b\x38") 

does exactly what I want, but how to convert the string?

+3
source share
2 answers

Whenever I see a string (incorrect), for example, consisting of this list of characters:

['\\', '\\', '6', '4', '\\', '\\', '2', 'e', '\\', '\\', '9', 'b', '\\', '\\', '3', '8']

when was this character list intended

['\x64', '\x2e', '\x9b', '\x38']

I am using the method decode('string_escape').

r'\\' r'\x'. replace(...).

In [37]: hexstring=r'\\64\\2e\\9b\\38'

In [38]: struct.unpack('f',(hexstring.replace(r'\\',r'\x').decode('string_escape')))
Out[38]: (7.3996168794110417e-05,)

In [39]: struct.unpack("f", "\x64\x2e\x9b\x38")
Out[39]: (7.3996168794110417e-05,)

PS. decode Python2, Python3. Python3 codecs.decode (err, Python2 unicode), decode . Python2 unicode, , 'string_escape', . , - .

Python3 hexstring.decode('string_encode') codecs.escape_decode(hexstring)[0].

: , jsbueno , binascii.unhexlify:

In [76]: import binascii
In [81]: hexstring=r"\\64\\2e\\9b\\38"
In [82]: hexstring.replace('\\','')
Out[82]: '642e9b38'

In [83]: binascii.unhexlify(hexstring.replace('\\',''))
Out[83]: 'd.\x9b8'

timeit , binascii.unhexlify :

In [84]: %timeit binascii.unhexlify(hexstring.replace('\\',''))
1000000 loops, best of 3: 1.42 us per loop

In [85]: %timeit hexstring.replace('\\','').decode('hex_codec')
100000 loops, best of 3: 2.94 us per loop

In [86]: %timeit hexstring.replace(r'\\',r'\x').decode('string_escape')
100000 loops, best of 3: 2.13 us per loop

:

. , , 4 , . .

+6

, "\" python , "hex_codec":

struct.unpack("f", "\\64\\2e\\9b\\38".replace("\\", "\").decode("hex_codec"))
0
source

Source: https://habr.com/ru/post/1772674/


All Articles