更新時間:2023-11-16 來源:黑馬程序員 瀏覽量:
在Python中,我們可以使用不同進(jìn)制表示數(shù)字,比如二進(jìn)制、八進(jìn)制、十六進(jìn)制等。以下是如何使用這些進(jìn)制的示例:
十進(jìn)制轉(zhuǎn)二進(jìn)制、八進(jìn)制、十六進(jìn)制
decimal_number = 25 binary_number = bin(decimal_number) # 十進(jìn)制轉(zhuǎn)二進(jìn)制 octal_number = oct(decimal_number) # 十進(jìn)制轉(zhuǎn)八進(jìn)制 hexadecimal_number = hex(decimal_number) # 十進(jìn)制轉(zhuǎn)十六進(jìn)制 print(f"Binary: {binary_number}") print(f"Octal: {octal_number}") print(f"Hexadecimal: {hexadecimal_number}")
二進(jìn)制、八進(jìn)制、十六進(jìn)制轉(zhuǎn)十進(jìn)制
binary_number = '11001' octal_number = '31' hexadecimal_number = '19' decimal_from_binary = int(binary_number, 2) # 二進(jìn)制轉(zhuǎn)十進(jìn)制 decimal_from_octal = int(octal_number, 8) # 八進(jìn)制轉(zhuǎn)十進(jìn)制 decimal_from_hex = int(hexadecimal_number, 16) # 十六進(jìn)制轉(zhuǎn)十進(jìn)制 print(f"Decimal from Binary: {decimal_from_binary}") print(f"Decimal from Octal: {decimal_from_octal}") print(f"Decimal from Hexadecimal: {decimal_from_hex}")
binary_number_1 = 0b1010 # 前綴 0b 表示二進(jìn)制數(shù) binary_number_2 = 0b1111 result_binary = bin(binary_number_1 + binary_number_2) # 二進(jìn)制加法 print(f"Result in Binary: {result_binary}")
上述代碼示例展示了如何在Python中進(jìn)行進(jìn)制轉(zhuǎn)換和使用不同進(jìn)制的數(shù)字進(jìn)行運(yùn)算。我們可以根據(jù)需要轉(zhuǎn)換不同進(jìn)制的數(shù)字,并且在這些進(jìn)制之間進(jìn)行轉(zhuǎn)換和操作。