- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary.py
More file actions
Latest commit
73 lines (57 loc) · 1.86 KB
/
Copy pathbinary.py
File metadata and controls
73 lines (57 loc) · 1.86 KB
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
65
66
67
68
69
70
71
72
73
importre
importtime
defget_input():
num_regex=re.compile(r"^\d+(?:\.\d{,30})?$")
input_str=input("Input a decimal: ")
whilenum_regex.match(input_str) isNone:
input_str=input("Nope, not valid. Give me another: ")
returninput_str
defallocate_bits(binary):
length=len(binary)
iflength<4:
rem=4-length
else:
rem=length%4
foriinrange(0, rem):
binary=binary+"0"
returnbinary
defcalculate_first_half(input_str):
num_array=str(float(input_str)).split('.') # Split the float as string on decimal place
integer=num_array[0]
before=""
finished=False
whilenotfinished:
divided=int(int(integer) /2)
remainder=int(integer) %2
before=before+str(remainder)
integer=divided
ifdivided==0:
finished=True
before=allocate_bits(before)
first_half=before[::-1] # Flips the string
returnfirst_half
defcalculate_second_half(input_str):
num_array=str(float(input_str)).split('.') # Split the float as string on decimal place
decimal=float(input_str) -int(num_array[0])
after=""
finished=False
whilenotfinished:
times_by_2=decimal*2
halves=str(float(times_by_2)).split('.')
decimal=times_by_2-int(halves[0])
after=after+halves[0]
iffloat(decimal) ==0.0:
finished=True
after=allocate_bits(after)
returnafter
defcovert_decimal_to_binary(input_val):
first_half=calculate_first_half(input_val)
second_half=calculate_second_half(input_val)
returnfirst_half+"."+second_half
defmain():
decimal=get_input() # Float Returned as string
start=time.time()
binary=covert_decimal_to_binary(decimal)
print(binary)
print(time.time() -start)
main()