简体   繁体   English

将整数转换为 32 位二进制 Python

[英]Convert an Integer into 32bit Binary Python

I am trying to make a program that converts a given integer(limited by the value 32 bit int can hold) into 32 bit binary number.我正在尝试制作一个将给定整数(受 32 位 int 可以容纳的值限制)转换为 32 位二进制数的程序。 For example 1 should return (000..31times)1.例如 1 应该返回 (000..31times)1。 I have been searching the documents and everything but haven't been able to find some concrete way.我一直在搜索文档和所有内容,但一直无法找到一些具体的方法。 I got it working where number of bits are according to the number size but in String.我让它在位数根据数字大小但在字符串中工作。 Can anybody tell a more efficient way to go about this?谁能告诉一个更有效的方法来解决这个问题?

'{:032b}'.format(n) where n is an integer. '{:032b}'.format(n)其中n是一个整数。 If the binary representation is greater than 32 digits it will expand as necessary:如果二进制表示大于 32 位,它将根据需要进行扩展:

>>> '{:032b}'.format(100)
'00000000000000000000000001100100'
>>> '{:032b}'.format(8589934591)
'111111111111111111111111111111111'
>>> '{:032b}'.format(8589934591 + 1)
'1000000000000000000000000000000000'    # N.B. this is 33 digits long

You can just left or right shift integer and convert it to string for display if you need.如果需要,您可以左移或右移整数并将其转换为字符串以进行显示。

>>> 1<<1
2
>>> "{:032b}".format(2)
'00000000000000000000000000000010'
>>>

or if you just need a binary you can consider bin或者如果你只需要一个二进制文件,你可以考虑 bin

>>> bin(4)
'0b100'

Say for example the number you want to convert into 32 bit binary is 4. So, num=4.比如说你想转换成 32 位二进制的数字是 4。所以,num=4。 Here is the code that does this: "s" is the empty string initially.这是执行此操作的代码:“s”最初是空字符串。

for i in range(31,-1,-1):
    cur=(num>>i) & 1 #(right shift operation on num and i and bitwise AND with 1)
    s+=str(cur)
print(s)#s contains 32 bit binary representation of 4(00000000000000000000000000000100)

00000000000000000000000000000100

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM