1. 程式人生 > >【python】字符串、16進制等數據處理

【python】字符串、16進制等數據處理

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進制等數據處理