Convert an Integer into 32bit Binary Python
35,128
Solution 1
'{: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
Solution 2
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'
Related videos on Youtube
Author by
Pooja Gupta
Updated on July 09, 2022Comments
-
Pooja Gupta almost 2 years
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?
-
Josh KelleyPossible duplicate of python convert to binary and keep leading zeros
-
-
Pooja Gupta about 7 yearsBut this returns a string,I need a binary number because I want to add features like left shift and right shift also.
-
juanpa.arrivillaga about 7 years@PoojaGupta You are looking for an
int
-
Scott over 2 yearsHow about converting negative values?