Python 程式將十六進位制字串轉換為十進位制


在本文中,我們將瞭解以下問題陳述的解決方案。

問題陳述 − 給定一個十六進位制字串,我們需要將其轉換為十進位制等價物。

我們可以透過以下兩種方法來解決此問題−

  • 蠻力法
  • 使用內建模組

蠻力法

在此,我們藉助顯式型別轉換函式即 integer。此函式接受兩個引數,即十六進位制等價物和基數,即 (16)。此函式用於將十六進位制字串轉換為其等效的十進位制整數型別,然後可以進一步將其型別轉換回字串格式。

示例

 現場演示

#input string
string = 'F'
# converting hexadecimal string to decimal
res = int(string, 16)
# print result
print("The decimal number associated with hexadecimal string is : " + str(res))

輸出

The decimal number associated with hexadecimal string is: 15

使用內建“ast”模組

在此,我們使用 ast 模組中提供的 literal_eval 函式,我們可以預測給定十六進位制等價物的基數,然後將其轉換為十進位制等價物。在此,我們使用文字求值的概念。

示例

 現場演示

# using built-in module literal_eval
from ast import literal_eval
# initializing string
test_string = '0xF'
# converting hexadecimal string to decimal
res = literal_eval(test_string)
# print result
print("The decimal number of the hexadecimal string is : " + str(res))

輸出

The decimal number of the hexadecimal string is: 15

所有變數均在本地作用域中宣告,在上圖中可以看到對它們的引用。

結論

在本文中,我們學習了將給定的十六進位制字串轉換為十進位制等價物的方法。

上次更新:2019 年 12 月 23 日

399 次觀看

開啟您的事業

完成課程認證

開始
廣告
© . All rights reserved.