Python hex() 函式



Python 的hex()函式用於將整數轉換為十六進位制(基數為 16)格式。

十六進位制是一種使用 16 個數字的數字系統,其中前十個與十進位制系統(0-9)相同,後六個由字母A 到 F(或 a-f)表示,分別對應於值10 到 15。當你在 Python 中使用 hex() 函式時,它會將十進位制數轉換為其十六進位制表示形式,結果是一個以“0x”開頭後跟十六進位制數字的字串。

語法

以下是 python hex() 函式的語法:

hex(x)

引數

此函式接受一個整數值作為其引數。

返回值

此函式返回一個字串,表示給定整數的十六進位制值。

示例 1

以下是 Python hex() 函式的一個示例。在這裡,我們將整數“111”轉換為其十六進位制表示形式:

integer_number = 111
hexadecimal_number = hex(integer_number)
print('The hexadecimal value obtained is:', hexadecimal_number)

輸出

以下是上述程式碼的輸出:

The hexadecimal value obtained is: 0x6f

示例 2

在這裡,我們使用 hex() 函式將二進位制值和八進位制值轉換為其相應的十六進位制表示形式:

binary_number = 0b1010
octal_number = 0o77
binary_to_hexadecimal = hex(binary_number)
octal_to_hexadecimal = hex(octal_number)
print('The hexadecimal value of binary number is:', binary_to_hexadecimal)
print('The hexadecimal value of octal number is:', octal_to_hexadecimal)

輸出

獲得的輸出如下:

The hexadecimal value of binary number is: 0xa
The hexadecimal value of octal number is: 0x3f

示例 3

現在,我們將使用 hex() 函式將整數值“2108”轉換為其十六進位制表示形式時,從輸出中刪除“0x”字首:

integer_number = 2108
hexadecimal_noprefix = hex(integer_number)[2:]
print('The hexadecimal value of the integer without prefix is:', hexadecimal_noprefix)

輸出

產生的結果如下:

The hexadecimal value of the integer without prefix is: 83c

示例 4

如果我們將非整數值傳遞給 hex() 函式,它將引發 TypeError。

這裡我們將透過將浮點數“11.21”傳遞給 hex() 函式來演示 TypeError:

# Example to demonstrate TypeError
floating_number = 11.21
hexadecimal_number = hex(floating_number)
print('The hexadecimal value of the floating number is:', hexadecimal_number)

輸出

我們可以在輸出中看到我們得到了一個 TypeError,因為我們已將浮點數傳遞給了 hex() 函式:

Traceback (most recent call last):
  File "C:\Users\Lenovo\Desktop\untitled.py", line 3, in <module>
    hexadecimal_number = hex(floating_number)
TypeError: 'float' object cannot be interpreted as an integer

示例 5

由於十六進位制以基數為 16 的表示法表示數字,因此我們可以透過使用 float.hex() 函式而不是常規的 hex() 函式來處理 TypeError。

# Example without TypeError
floating_number = 11.21
hexadecimal_number = float.hex(floating_number)
print('The hexadecimal value of the floating number is:', hexadecimal_number)

輸出

程式碼的輸出如下:

The hexadecimal value of the floating number is: 0x1.66b851eb851ecp+3
python_type_casting.htm
廣告