数制转换python的算法设计
时间: 2024-01-13 16:20:23 浏览: 100
数据结构课程设计数制转换.doc
以下是一个用Python实现的数制转换算法的例子:
```python
def decimal_to_binary(decimal):
binary = ""
while decimal > 0:
binary = str(decimal % 2) + binary
decimal = decimal // 2
return binary
def binary_to_decimal(binary):
decimal = 0
power = 0
for digit in binary[::-1]:
decimal += int(digit) * (2 ** power)
power += 1
return decimal
def decimal_to_hexadecimal(decimal):
hexadecimal = ""
while decimal > 0:
remainder = decimal % 16
if remainder < 10:
hexadecimal = str(remainder) + hexadecimal
else:
hexadecimal = chr(ord('A') + remainder - 10) + hexadecimal
decimal = decimal // 16
return hexadecimal
def hexadecimal_to_decimal(hexadecimal):
decimal = 0
power = 0
for digit in hexadecimal[::-1]:
if digit.isdigit():
decimal += int(digit) * (16 ** power)
else:
decimal += (ord(digit.upper()) - ord('A') + 10) * (16 ** power)
power += 1
return decimal
```
这个例子中包含了四个函数,分别用于十进制转二进制、二进制转十进制、十进制转十六进制和十六进制转十进制。你可以根据需要调用这些函数来进行数制转换。
阅读全文