简体   繁体   中英

Python: converting hex values, stored as string, to hex data

(Answer found. Close the topic)

I'm trying to convert hex values, stored as string, in to hex data.

I have:

data_input = 'AB688FB2509AA9D85C239B5DE16DD557D6477DEC23AF86F2AABD6D3B3E278FF9'

I need:

data_output = '\xAB\x68\x8F\xB2\x50\x9A\xA9\xD8\x5C\x23\x9B\x5D\xE1\x6D\xD5\x57\xD6\x47\x7D\xEC\x23\xAF\x86\xF2\xAA\xBD\x6D\x3B\x3E\x27\x8F\xF9'

I was trying data_input.decode('hex') , binascii.unhexlify(data_input) but all they return:

"\xabh\x8f\xb2P\x9a\xa9\xd8\\#\x9b]\xe1m\xd5W\xd6G}\xec#\xaf\x86\xf2\xaa\xbdm;>'\x8f\xf9"

What should I write to receive all bytes in '\\xFF' view?


updating :

I need representation in '\\xFF' view to write this data to a file (I'm opening file with 'wb') as:

«hЏІPљ©Ш\#›]бmХWЦG}м#Ї†тЄЅm;>'Џщ

update2

Sorry for bothering. An answer lies under my nose all the time:

data_output = data_input.decode('hex')
write_file(filename, data_output)  #just opens a file 'wb', ant write a data in it

gives the same result as I need

I like chopping strings into fixed-width chunks using re.findall

print '\\x' + '\\x'.join(re.findall('.{2}', data_input))

If you want to actually convert the string into a list of ints, you can do that like this:

data = [int(x, 16) for x in re.findall('.{2}', data_input)]

It's an inefficient solution, but there's always:

flag = True
data_output = ''
for char in data_input:
    if flag:
        buffer = char
        flag = False
    else:
        data_output = data_output + '\\x' + buffer + char
        flag = True

EDIT HOPEFULLY THE LAST: Who knew I could mess up in so many different ways on that simple a loop? Should actually run now...

>>> int('0x10AFCC', 16)
1093580
>>> hex(1093580)
'0x10afcc'

So prepend your string with '0x' then do the above

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM