13

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. For example 1 should return (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?

4
  • 1
    Possible duplicate of python convert to binary and keep leading zeros Commented Mar 26, 2017 at 2:41
  • Can you show us some code Commented Mar 26, 2017 at 2:43
  • Are you looking for 2's complement representation? Commented Mar 26, 2017 at 5:10
  • Yes, I want this representation because I am trying to build an webapp which mimics the Assembler(with limited functionality) Commented Mar 27, 2017 at 4:13

5 Answers 5

31

'{:032b}'.format(n) where n is an integer. If the binary representation is greater than 32 digits it will expand as necessary:

>>> '{:032b}'.format(100)
'00000000000000000000000001100100'
>>> '{:032b}'.format(8589934591)
'111111111111111111111111111111111'
>>> '{:032b}'.format(8589934591 + 1)
'1000000000000000000000000000000000'    # N.B. this is 33 digits long
Sign up to request clarification or add additional context in comments.

3 Comments

But this returns a string,I need a binary number because I want to add features like left shift and right shift also.
@PoojaGupta You are looking for an int
How about converting negative values?
7

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(4)
'0b100'

Comments

1
x = 1234
print(f"{x:032b}")  # 00000000000000000000010011010010

Comments

0

Say for example the number you want to convert into 32 bit binary is 4. So, num=4. Here is the code that does this: "s" is the empty string initially.

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

Comments

0

Lets say

a = 4
print(bin(a))  # 0b101

For the output you may append 0s from LSB to till 101 to get the 32bit address for the integer - 4. If you don't want 0b you may slice it

print(bin(a)[-3:])  # 101

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.