十六进制 str 到 bytes 的转换

概述

  这里记录做 ctf 题目过程中编写 python 脚本常碰到的字符和字节的转换问题,不同于一般的字符串转字节,和二进制打交道遇到的都是以字符串形式表示的十六进制串,需要将其转换为字节做进一步的处理,所以才有了本篇博客的记录点。

str ⇒ bytes

  python 代码如下。



# res 为测试样本
res = "B75285C190E907B8E41AC3BD1D8E8546002144AFEF7032B511C6"


# method one
import binascii

data = binascii.unhexlify(res)
print(data, type(data))
# b'\xb7R\x85\xc1\x90\xe9\x07\xb8\xe4\x1a\xc3\xbd\x1d\x8e\x85F\x00!D\xaf\xefp2\xb5\x11\xc6' <class 'bytes'>


# method two
data = bytearray.fromhex(res)
print(data, type(data))
# bytearray(b'\xb7R\x85\xc1\x90\xe9\x07\xb8\xe4\x1a\xc3\xbd\x1d\x8e\x85F\x00!D\xaf\xefp2\xb5\x11\xc6') <class 'bytearray'>


# method three
data = []
for i in range(0, 52, 2):
    data.append(int(res[i:i+2], 16))
data = bytes(data)
print(data, type(data))
# b'\xb7R\x85\xc1\x90\xe9\x07\xb8\xe4\x1a\xc3\xbd\x1d\x8e\x85F\x00!D\xaf\xefp2\xb5\x11\xc6' <class 'bytes'>

总结

不忘初心,砥砺前行!

Logo

技术共进,成长同行——讯飞AI开发者社区

更多推荐