1.hex字符串和byte类型数据的转换
搜索了一堆有关转换的教程,都是些老旧的decode、encode,在python3.5以上根本不存在这些编码方式了。
在python3.7中可以使用如下函数直接实现。
bytes数据转换为hex字符串——bytes.hex()
#bytes数据转hex字符串
data_bytes = b"h8679\x00\x07S\x00\x00\x00\x00\x00\x00\x16"
data_hex = bytes.hex(data_bytes)
print(data_hex)
print(type(data_hex))
print(type(data_bytes))
输出的结果如下图:
hex字符串转换为bytes数据——bytes.fromhex()
#hex字符串转换为bytes数据
data_hex = "683836373900075300000000000016"
data_bytes = bytes.fromhex(data_hex)
print(data_bytes)
print(type(data_hex))
print(type(data_bytes))
输出的结果如下图:
2.進制轉換
hex字符串转换为10進制int——int(str,16)
>>> int('10',16)
16
10進制int转换为16進制字符串——hex()
>>> hex(16)
'0x10'
10進制int转换为2進制字符串——bin()
>>> bin(10)
'0b1010'
3.ASCII碼轉換
ASCII字符轉換為10進制int——ord()
>>> ord('A')
65
10進制int轉換為ASCII字符——chr()
>>> chr(65)
'A'