python实现进制转换
时间: 2023-09-27 18:09:03 浏览: 145
可以使用Python内置的函数来实现进制转换,如下所示:
1. 十进制转二进制:
```python
dec = 10
bin_dec = bin(dec)
print(bin_dec) # 输出0b1010
```
2. 十进制转八进制:
```python
dec = 10
oct_dec = oct(dec)
print(oct_dec) # 输出0o12
```
3. 十进制转十六进制:
```python
dec = 10
hex_dec = hex(dec)
print(hex_dec) # 输出0xa
```
4. 二进制转十进制:
```python
bin_dec = '1010'
dec = int(bin_dec, 2)
print(dec) # 输出10
```
5. 八进制转十进制:
```python
oct_dec = '12'
dec = int(oct_dec, 8)
print(dec) # 输出10
```
6. 十六进制转十进制:
```python
hex_dec = 'a'
dec = int(hex_dec, 16)
print(dec) # 输出10
```
注意:在二进制、八进制和十六进制数字前面都有一个特殊的前缀,分别是0b、0o和0x。如果要进行进制转换,需要先去掉前缀,再使用int()函数将其转换为十进制。
相关问题
Python实现进制转换
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`是转换后得到的二进制、八进制和十六进制数。
用python实现进制转换代码
在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)
```
阅读全文