用python实现进制转换代码
时间: 2024-10-13 08:14:00 浏览: 25
在Python中,可以使用内置的函数或者简单的算术运算来实现数字之间的进制转换。以下是两个常见的例子:
1. **将十进制转为其他进制**(如二进制、八进制、十六进制):
```python
def convert_base(number, base):
return format(number, f'0{base}b') if base == 2 else \
format(number, f'0{base}o') if base == 8 else \
format(number, '0{base}x').upper() # 十六进制首字母大写
# 示例
decimal_num = 42
binary = convert_base(decimal_num, 2)
octal = convert_base(decimal_num, 8)
hexadecimal = convert_base(decimal_num, 16)
```
2. **将字符串形式的其他进制转换为十进制**:
```python
def str_to_decimal(binary_string, octal_string, hex_string):
return int(binary_string, 2), int(octal_string, 8), int(hex_string, 16)
# 示例
binary_str = '1010'
octal_str = '52'
hex_str = '2a'
decimals = str_to_decimal(binary_str, octal_str, hex_str)
```
阅读全文