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

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

问题描述

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

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"

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

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

或从Python 2.7和Python 3.0开始:

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

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

请注意,bytesbytearray的不变版本.

Note that bytes is an immutable version of bytearray.

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

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