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

所有變數均在本地作用域中宣告,在上圖中可以看到對它們的引用。
結論
在本文中,我們學習了將給定的十六進位制字串轉換為十進位制等價物的方法。
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP