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

查看:99
本文介绍了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
"xdexadxbexef"

或从 Python 2.7 和 Python 3.0 开始:

>>> bytes.fromhex(hex_string)  # Python ≥ 3
b'xdexadxbexef'

>>> bytearray.fromhex(hex_string)
bytearray(b'xdexadxbexef')

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

Note that bytes is an immutable version of bytearray.

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

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