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 5.6k 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
4 Answers
30
'{: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
- 84,695
- 9
- 117
- 138
-
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
-
1
6
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
- 3,676
- 1
- 21
- 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
- 30,962
- 25
- 85
- 135
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

buhtz
- 10,774
- 18
- 76
- 149

B S Mahesh Kumar
- 61
- 4