非十进制转十进制全代码
时间: 2024-10-05 10:02:49 浏览: 23
非十进制数转换为十进制数通常涉及到基数转换,特别是在计算机科学中处理二进制、八进制和十六进制等。这里是一个简单的Python示例,展示了如何将其他进制的数字转换为十进制:
```python
def convert_base_to_decimal(input_string, base):
if base == 2: # Binary to Decimal
return int(input_string, 2)
elif base == 8: # Octal to Decimal
return int(input_string, 8)
elif base == 16: # Hexadecimal to Decimal
return int(input_string, 16)
else:
raise ValueError("Unsupported base. Only binary (2), octal (8) and hexadecimal (16) are supported.")
# 示例
binary_num = "1010"
decimal_num = convert_base_to_decimal(binary_num, 2)
print(f"{binary_num} in decimal is {decimal_num}")
octal_num = "52"
decimal_num_octal = convert_base_to_decimal(octal_num, 8)
print(f"{octal_num} in decimal is {decimal_num_octal}")
hex_num = "A4"
decimal_num_hex = convert_base_to_decimal(hex_num, 16)
print(f"{hex_num} in decimal is {decimal_num_hex}")
```
在这个例子中,`convert_base_to_decimal`函数接受一个字符串表示的非十进制数以及它的基数,然后返回相应的十进制值。
阅读全文