如何在 Python 中指定十六進位制和八進位制整數?


十六進位制和八進位制是 Python 中數值型別的一部分。讓我們看看如何逐一指定它們。

對於十六進位制型別,新增前導 0x。例如 -

0x11

對於八進位制型別(基數 8),新增前導 0(零)。例如 -

0O20

Python 中的十六進位制整數

十六進位制數系統使用 10 個數字和 6 個字母,0、1、2、3、4、5、6、7、8、9、A、B、C、D、E、F。字母表示從 10 開始的數字。A = 10。B = 11,C = 12,D = 13,E = 14,F = 15。也稱為基數 16 數系統。

示例

要表示十六進位制型別,請新增前導 0x -

a = 0x12 print("Hexadecimal = ",a) print("Type = ",type(a))

輸出

Hexadecimal = 18
Type = <class 'int'>

Python 中的八進位制整數

八進位制數使用八個數字,0、1、2、3、4、5、6、7。也稱為基數 8 數系統。八進位制數中的每個位置都表示基數(8)的 0 次冪。八進位制數中的最後一個位置表示基數(8)的 x 次冪。

示例

要表示八進位制型別(基數 8),請新增前導 0(零) -

a = 0O20 print("Octal = ",a) print("Type = ",type(a))

輸出

Octal = 16
Type = <class 'int'>

讓我們看看其他示例 -

將十進位制轉換為八進位制

示例

要將十進位制轉換為八進位制,請使用 oct() 方法並將十進位制數設定為引數 -

# Decimal Number dec = 110 # Display the Decimal Number print("Decimal = ",dec) # Display the Octal form print('The number {} in octal form = {}'.format(dec, oct(dec)))

輸出

Decimal = 110
The number 110 in octal form = 0o156

將十進位制轉換為十六進位制

要將十進位制轉換為十六進位制,請使用 hex() 方法並將十進位制數設定為引數 -

示例

# Decimal Number dec = 110 # Display the Decimal Number print("Decimal = ",dec) # Display the Hexadecimal form print('The number {} in hexadecimal form = {}'.format(dec, hex(dec)))

輸出

Decimal =  110
The number 110 in hexadecimal form = 0x6e

更新於: 2022-09-16

7K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.