Python实现进制转换
时间: 2023-11-05 14:22:23 浏览: 109
Python可以通过内置的函数来实现进制转换。下面是几个常见的进制转换方法的示例:
1. 十进制转二进制:
```python
decimal_number = 42
binary_number = bin(decimal_number)[2:]
print(binary_number)
```
2. 十进制转八进制:
```python
decimal_number = 42
octal_number = oct(decimal_number)[2:]
print(octal_number)
```
3. 十进制转十六进制:
```python
decimal_number = 42
hexadecimal_number = hex(decimal_number)[2:]
print(hexadecimal_number)
```
4. 二进制转十进制:
```python
binary_number = "101010"
decimal_number = int(binary_number, 2)
print(decimal_number)
```
5. 八进制转十进制:
```python
octal_number = "52"
decimal_number = int(octal_number, 8)
print(decimal_number)
```
6. 十六进制转十进制:
```python
hexadecimal_number = "2A"
decimal_number = int(hexadecimal_number, 16)
print(decimal_number)
```
这些示例中,变量`decimal_number`是要进行转换的十进制数,而变量`binary_number`、`octal_number`、`hexadecimal_number`是转换后得到的二进制、八进制和十六进制数。
阅读全文