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?
Asked
Active
Viewed 3.9k times
12
-
1Possible duplicate of [python convert to binary and keep leading zeros](http://stackoverflow.com/questions/16926130/python-convert-to-binary-and-keep-leading-zeros) – Josh Kelley Mar 26 '17 at 02:41
-
Can you show us some code – jcarder Mar 26 '17 at 02:43
-
Are you looking for 2's complement representation? – Jithin Pavithran Mar 26 '17 at 05:10
-
Yes, I want this representation because I am trying to build an webapp which mimics the Assembler(with limited functionality) – Pooja Gupta Mar 27 '17 at 04:13
3 Answers
23
'{: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
mhawke
- 80,261
- 9
- 108
- 134
-
But this returns a string,I need a binary number because I want to add features like left shift and right shift also. – Pooja Gupta Mar 26 '17 at 03:02
-
2
-
5
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'
Andy Wong
- 2,821
- 1
- 18
- 18
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
Dharman
- 26,923
- 21
- 73
- 125