【python】字串、16進位等資料處理

來源:互聯網
上載者:User

標籤: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進位等資料處理

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.