python中将十进制转化为二进制
时间: 2023-11-22 09:49:56 浏览: 96
以下是两种Python将十进制转化为二进制的方法:
1. 将十进制数字转换为二进制,使用栈实现:
```python
def tenTOtwo(number):
# 定义栈
s=[]
binstring=''
while number>0:
# 余数出栈
rem=number%2
s.append(rem)
number=number//2
while len(s)>0:
# 元素全部出栈即为所求二进制数
binstring=binstring+str(s.pop())
print(binstring)
```
2. 将十进制字符转换为6位二进制,不足6位用0在前面补足:
```python
def tenTOtwo6(number):
# 定义栈
s=[]
binstring=''
number=int(number)
while number>0:
# 余数出栈
rem=number%2
s.append(rem)
number=number//2
while len(s)>0:
# 元素全部出栈即为所求二进制数
binstring=binstring+str(s.pop())
while len(binstring)<6:
c=6-len(binstring)
binstring='0'*c+binstring
return binstring
```
阅读全文
相关推荐
![py](https://img-home.csdnimg.cn/images/20250102104920.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.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)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20250102104920.png)