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?
-
1Possible duplicate of python convert to binary and keep leading zerosJosh Kelley– Josh Kelley2017-03-26 02:41:18 +00:00Commented Mar 26, 2017 at 2:41
-
Can you show us some codejc22920– jc229202017-03-26 02:43:46 +00:00Commented Mar 26, 2017 at 2:43
-
Are you looking for 2's complement representation?Jithin Pavithran– Jithin Pavithran2017-03-26 05:10:46 +00:00Commented 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)Pooja Gupta– Pooja Gupta2017-03-27 04:13:30 +00:00Commented Mar 27, 2017 at 4:13
Add a comment
|
5 Answers
'{: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
3 Comments
Pooja Gupta
But this returns a string,I need a binary number because I want to add features like left shift and right shift also.
juanpa.arrivillaga
@PoojaGupta You are looking for an
intScott
How about converting negative values?
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