diff --git a/jz.py b/jz.py new file mode 100644 index 0000000..177a5c2 --- /dev/null +++ b/jz.py @@ -0,0 +1,27 @@ +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