简体   繁体   English

Python:将存储为字符串的十六进制值转换为十六进制数据

[英]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: 我正在尝试data_input.decode('hex')binascii.unhexlify(data_input)但它们都返回:

"\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? 我应该写什么来接收'\\ xFF'视图中的所有字节?


updating : 更新

I need representation in '\\xFF' view to write this data to a file (I'm opening file with 'wb') as: 我需要在'\\ xFF'视图中表示,才能将此数据写入文件(我正在用'wb'打开文件),如下所示:

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

update2 更新2

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 我喜欢使用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 因此,请在字符串前添加“ 0x”,然后执行上述操作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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