使用Python進行十六進位制數字的解碼和編碼


在這篇文章中,我們將學習如何使用Python解碼和編碼十六進位制數字。

使用的方法

  • 使用binascii模組

  • 使用base64模組

方法1:使用Binascii模組

binascii模組中有多種方法可以轉換二進位制和不同的ASCII編碼二進位制表示形式。

如果只需要對原始十六進位制數字字串進行編碼或解碼,請使用**binascii模組**。

演算法(步驟)

以下是執行所需任務的演算法/步驟:−

  • 使用import關鍵字匯入**binascii**模組。

  • 建立一個變數來儲存**輸入位元組字串**。

  • 使用**binascii**模組的**b2a_hex()**函式將輸入位元組字串編碼為十六進位制數字。

  • 列印輸入位元組字串的結果十六進位制數字。

  • 使用**binascii**模組的**a2b_hex()**函式將上述十六進位制數字解碼回字節字串。

示例

下面的程式使用b2a_hex()和a2b_hex()函式將輸入位元組字串編碼為十六進位制數字,並將其解碼回字節字串−

# importing binascii module
import binascii

# input byte string 
inputByteString = b'tutorialspoint python'

# encoding input byte string into hexadecimal digits
hexdigits = binascii.b2a_hex(inputByteString)

# printing the resultant hexadecimal digits of the byte string 
print(hexdigits)

# decoding hexadecimal digits back into byte string 
print(binascii.a2b_hex(hexdigits))

輸出

執行上述程式後,將生成以下輸出:

b'7475746f7269616c73706f696e7420707974686f6e'
b'tutorialspoint python'

方法2:使用base64模組

**base64**模組也具有類似的功能。它也可以編碼或解碼原始十六進位制數字字串。

演算法(步驟)

以下是執行所需任務的演算法/步驟:−

  • 使用import關鍵字匯入**base64**模組。

  • 建立一個變數來儲存**輸入位元組字串**。

  • 使用**base64**模組的**b16encode()**函式將輸入位元組字串編碼為十六進位制數字。

  • 列印輸入位元組字串的結果十六進位制數字。

  • 使用**base64**模組的**b16decode()**函式將上述十六進位制數字解碼回字節字串並列印它。

示例

下面的程式使用b16encode()和b16decode()函式將輸入位元組字串編碼為十六進位制數字,並將其解碼回字節字串−

# importing base64 module
import base64

# input byte string 
inputByteString = b'tutorialspoint python'

# encoding input byte byte string into hexadecimal digits
# using b16encode() function of base64 module
hexdigits = base64.b16encode(inputByteString)

# printing the resultant hexadecimal digits of the byte string 
print(hexdigits)

# decoding hexadecimal digits back into byte string 
print(base64.b16decode(hexdigits))

輸出

執行上述程式後,將生成以下輸出:

b'7475746F7269616C73706F696E7420707974686F6E'
b'tutorialspoint python'

使用所描述的函式,十六進位制的轉換在大多數情況下很簡單。**大小寫摺疊**是兩種方法差異最大的地方。與binascii中的操作相反,**base64.b16decode()**和**base64.b16encode()**函式僅適用於**大寫**十六進位制字母。

同樣重要的是要記住,編碼函式的輸出始終是位元組字串。可能需要新增額外的解碼步驟才能強制其輸出為Unicode。

示例

下面的程式使用decode函式將十六進位制數字解碼回ASCII格式:

# importing base64 module
import base64
 
# input byte string 
inputByteString = b'tutorialspoint python'
 
# encoding input byte byte string into hexadecimal digits
# using b16encode() function of base64 module
hexdigits = base64.b16encode(inputByteString)
 
# printing the resultant hexadecimal digitsof the byte string 
print(hexdigits)
 
# decoding hexadecimal digits in ASCII format using the decode() function
print(hexdigits.decode('ascii'))

輸出

執行上述程式後,將生成以下輸出:

b'7475746F7269616C73706F696E7420707974686F6E'
7475746F7269616C73706F696E7420707974686F6E

b16decode()和a2b_hex()方法在解碼十六進位制數字時接受位元組或Unicode文字作為輸入。但是,這些字串只能包含經過ASCII編碼的十六進位制數字。

結論

在這篇文章中,我們學習瞭如何使用Python解碼和編碼數字十六進位制數字。我們還學習瞭如何使用decode()方法解碼十六進位制數字的ASCII表示。

更新於:2023年1月23日

4K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.