示例代码:
hexVar = '1D' # i need this to be dynamically allocated
var1 = '\\x' + hexVar
print "var1 len: ", len(var1) # gives me 4 instead of 1
在发送给袜子udp关联请求格式时,我需要将此var1设为1个字节
答案 0 :(得分:0)
您可以将文本转换为整数(以16为底),将下一个整数转换为char,然后使用代码b"\x1d"
将char编码为单字节
hexVar = '1D'
integer = int(hexVar, 16)
char = chr(integer)
var1 = char.encode()
print("var1 len: ", len(var1), var1) #
结果
var1 len: 1 b'\x1d'
编辑:
import binascii
hexVar = '1D'
var1 = binascii.a2b_hex(hexVar)
print("var1 len: ", len(var1), var1)
或
import binascii
hexVar = '1D'
var1 = binascii.unhexlify(hexVar)
print("var1 len: ", len(var1), var1)