十六进制字符串到python中的字节数组 [英] hexadecimal string to byte array in python

查看:29
本文介绍了十六进制字符串到python中的字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很长的十六进制字符串,代表一系列不同类型的值.我希望将此十六进制字符串转换为字节数组,以便我可以将每个值移出并将其转换为正确的数据类型.

解决方案

假设你的十六进制字符串是这样的

<预><代码>>>>hex_string =死牛肉"

将其转换为字符串(Python ≤ 2.7):

<预><代码>>>>hex_data = hex_string.decode("hex")>>>十六进制数据"\xde\xad\xbe\xef"

或自 Python 2.7 和 Python 3.0 起:

<预><代码>>>>bytes.fromhex(hex_string) # Python ≥ 3b'\xde\xad\xbe\xef'>>>bytearray.fromhex(hex_string)bytearray(b'\xde\xad\xbe\xef')

请注意,bytesbytearray 的不可变版本.

I have a long Hex string that represents a series of values of different types. I wish to convert this Hex String into a byte array so that I can shift each value out and convert it into its proper data type.

解决方案

Suppose your hex string is something like

>>> hex_string = "deadbeef"

Convert it to a string (Python ≤ 2.7):

>>> hex_data = hex_string.decode("hex")
>>> hex_data
"\xde\xad\xbe\xef"

or since Python 2.7 and Python 3.0:

>>> bytes.fromhex(hex_string)  # Python ≥ 3
b'\xde\xad\xbe\xef'

>>> bytearray.fromhex(hex_string)
bytearray(b'\xde\xad\xbe\xef')

Note that bytes is an immutable version of bytearray.

这篇关于十六进制字符串到python中的字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆