将数字转换为具有固定长度的二进制数 [英] Converting a number to binary with a fixed length
本文介绍了将数字转换为具有固定长度的二进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
0b
: pre $ key_one = int(raw_input(Enter key(0 <= key< = 127):))
如果key_one在范围(128)中:
bin_key_one = bin(key_one)[2:]
print bin_key_one
else:
print必须输入密钥(0 < key< = 127)
现在我想通过填充7个字符根据需要用零。我想我需要使用for循环,但有人可以告诉我怎么做吗?
解决方案
不,你不。
>>> '{0:07b}'。format(12)
'0001100'
Say I get a random number between 1 and 127. I change the number to binary and remove the 0b
from it with the fallowing code:
key_one= int(raw_input("Enter key (0 <= key <= 127): "))
if key_one in range(128):
bin_key_one=bin(key_one)[2:]
print bin_key_one
else:
print "You have to enter key (0 <= key <= 127)"
Now I want to make it 7-characters long by padding the beginning with zeros as necessary. I think I need to use a for loop, but can someone show me how to do it?
解决方案
No you don't.
>>> '{0:07b}'.format(12)
'0001100'
这篇关于将数字转换为具有固定长度的二进制数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文