標籤:python binascii 轉碼
最近做一個socket server,需要接收組播報文,並進行分析處理。其中涉及的一個問題是,待發送的報文是字串形式,類似“hello world”。
從wireshark截取的報文看,都是16進位資料,以為必須轉為該種類型才能發送,需要轉換為16進位字串,類似“0x\a00x\c30x\b4”等。
但後來發現,直接發送資料也是ok的,應該是資料發送時自己會進行轉碼。
不瞭解的時候,網上查了下,發現大家推薦用到的模組是binascii,查看help
幾個方法如下:
FUNCTIONS
a2b_base64(...)
(ascii) -> bin. Decode a line of base64 data
ASCII到BIN資料,解碼一段base64的資料--先不管,不是我所需要的
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進位表示符
【python】字串、16進位等資料處理