python栈进制转换代码
时间: 2023-10-12 15:21:24 浏览: 38
下面是一个将十进制数转换为二进制、八进制、十六进制的Python代码:
```python
def decimal_to_binary(decimal):
"""将十进制数转换为二进制"""
binary = ""
while decimal > 0:
binary = str(decimal % 2) + binary
decimal //= 2
return binary
def decimal_to_octal(decimal):
"""将十进制数转换为八进制"""
octal = ""
while decimal > 0:
octal = str(decimal % 8) + octal
decimal //= 8
return octal
def decimal_to_hexadecimal(decimal):
"""将十进制数转换为十六进制"""
hexadecimal = ""
while decimal > 0:
remainder = decimal % 16
if remainder < 10:
hexadecimal = str(remainder) + hexadecimal
else:
hexadecimal = chr(ord('A') + remainder - 10) + hexadecimal
decimal //= 16
return hexadecimal
```
使用方法:
```python
>>> decimal_to_binary(10)
'1010'
>>> decimal_to_octal(10)
'12'
>>> decimal_to_hexadecimal(10)
'A'
```
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)