将数字转换为固定长度的二进制数 [英] Converting a number to binary with a fixed length

查看:56
本文介绍了将数字转换为固定长度的二进制数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我得到一个介于 1 和 127 之间的随机数.我将这个数字更改为二进制,并使用空闲代码从中删除 0b:

key_one= int(raw_input("Enter key (0 <= key <= 127):"))如果 key_one 在范围内(128):bin_key_one=bin(key_one)[2:]打印 bin_key_one别的:打印您必须输入密钥(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆