-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert_num_to_binary.py
64 lines (43 loc) · 1.12 KB
/
convert_num_to_binary.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
'''
Below code can be used to convert Positive integers into
their respective Binaries.
Parameters: a number greater than 0
Output: It will return the Binary value as a string.
Author: K.Hari kiran
'''
def convert_bits(x):
if x == 0:
return 0
base = 2
quotient = x//base
power = 0
bits = {}
while True:
if x <= 0:
break
elif quotient > 1:
base *= 2
power += 1
quotient = x//base
elif quotient == 1:
x = x % base
power += 1
bits[power]=1
power = 0
base = 2
quotient = x//base
else:
bits[power] = 1
break
list = []
for i in range(50):
list.append (bits.get(i,0))
list.reverse()
first = list.index(1)
newlist = list[first:]
answer = ''
for j in newlist:
answer += str(j)
return answer
num = int(input("Enter a Positive integer: "))
print("Binary for given number is {0}".format(convert_bits(num)))