最近作一个socket server,须要接收组播报文,并进行分析处理。其中涉及的一个问题是,待发送的报文是字符串形式,相似“hello world”。git
从wireshark截取的报文看,都是16进制数据,觉得必须转为该种类型才能发送,须要转换为16进制字符串,相似“0x\a00x\c30x\b4”等。socket
但后来发现,直接发送数据也是ok的,应该是数据发送时本身会进行转码。ide
不了解的时候,网上查了下,发现你们推荐用到的模块是binascii,查看help函数
几个方法以下:编码
FUNCTIONS翻译
a2b_base64(...)code
(ascii) -> bin. Decode a line of base64 dataserver
ASCII到BIN数据,解码一段base64的数据--先无论,不是我所须要的
ci
a2b_hex(...)字符串
a2b_hex(hexstr) -> s; Binary data of hexadecimal representation.
二进制数据的十六进制表示--须要,由于最后数据要以16进制字符串形式
hexstr must contain an even number of hex digits (upper or lower case).
This function is also available as "unhexlify()"
参数hexstr必须是偶数个16进制字码--必须的,两个16进制字码组成一个ASCII码字
a2b_hqx(...)
ascii -> bin, done. Decode .hqx coding
先无论
a2b_qp(...)
Decode a string of qp-encoded data
先无论
a2b_uu(...)
(ascii) -> bin. Decode a line of uuencoded data
先无论
b2a_base64(...)
(bin) -> ascii. Base64-code line of data
b2a_hex(...)
b2a_hex(data) -> s; Hexadecimal representation of binary data.
看这个翻译:二进制数据的16进制表示,貌似与上面那个同样。
先试试看:
>>>t = binascii.b2a_hex('hello world')
'68656c6c6f20776f726c64'
>>> binascii.a2b_hex(t)
'hello world'
>>> binascii.a2b_hex("e4bda0e5a5bde59564")
'\xe4\xbd\xa0\xe5\xa5\xbd\xe5\x95d'
第一个函数是把字符串编码为16进制字符串
第二个函数是把16进制字符串加了16进制表示符