Created
June 7, 2020 19:45
-
-
Save anupkalburgi/97bb96aef98f016172740754cec6c048 to your computer and use it in GitHub Desktop.
decimal_to_binary.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1 def decimal_to_binary(num, rems): | |
2 if num == 0: | |
3 return rems[::-1] | |
4 else: | |
5 rem = num % 2 | |
6 rems.append(rem) | |
7 return decimal_to_binary(num // 2, rems) | |
8 | |
9 assert decimal_to_binary(193, []) == [1,1,0,0,0,0,0,1] | |
10 | |
11 | |
12 def binary_to_decimal(binary, place_value, decimal_value): | |
13 ''' | |
14 assuming the binary is numbers are given in list like [1,1,0,0,0,0,0,1] | |
15 return back 193 | |
16 counting from right to left is more convinent, as the base value goes on increasing by 2 every time | |
17 ''' | |
18 if binary == []: | |
19 return decimal_value | |
20 else: | |
21 last_bit = binary.pop() | |
22 return binary_to_decimal(binary, place_value *2, decimal_value + place_value * last_bit) | |
23 | |
24 assert binary_to_decimal([1,1,0,0,0,0,0,1], 1, 0) == 193 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment