You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

28 lines
789 B

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

def convert_base(num, from_base, to_base):
# 将输入数从原始进制转换为十进制
decimal_num = int(str(num), from_base)
# 将十进制数转换为目标进制
if decimal_num == 0:
return '0'
digits = []
while decimal_num > 0:
remainder = decimal_num % to_base
if remainder >= 10:
digits.append(chr(ord('A') + remainder - 10))
else:
digits.append(str(remainder))
decimal_num //= to_base
# 反转数字列表并连接成字符串
result = ''.join(digits[::-1])
return result
# 示例将二进制数1011转换为十六进制数
num = "1011"
from_base = 2
to_base = 16
converted_num = convert_base(num, from_base, to_base)
print(converted_num) # 输出结果为B