Reputation: 97
I basically finished everything.. I just can't find a way to multiply each integer by 2^0, 2^1 ... and so on Here is my code
def BinaryToDecimal(binaryString):
if len(binaryString) == 0:
return 0
else:
return int(binaryString[-1:])*(2**(4-len(binaryString))) + BinaryToDecimal(binaryString[:len(binaryString)-1])
If I have input '1000', I return last digit of the string and do recursion by eliminating the last digit so, '1000' --> '100' --> '10' and so on
The problem here is that I just cannot find a way to multiply last digit by its corresponding power of 2. Any thought of how to get 0,1,2,3 when length of binary string is 4,3,2,1 ?
Upvotes: 1
Views: 7129
Reputation: 55489
You're making this more complicated than it needs to be. No power calculation is required.
def binary_to_decimal(bstring):
if not bstring:
return 0
return binary_to_decimal(bstring[:-1]) * 2 + int(bstring[-1])
# Test
for i in range(16):
b = format(i, 'b')
n = binary_to_decimal(b)
print('{:2} {:4} -> {}'.format(i, b, n))
output
0 0 -> 0
1 1 -> 1
2 10 -> 2
3 11 -> 3
4 100 -> 4
5 101 -> 5
6 110 -> 6
7 111 -> 7
8 1000 -> 8
9 1001 -> 9
10 1010 -> 10
11 1011 -> 11
12 1100 -> 12
13 1101 -> 13
14 1110 -> 14
15 1111 -> 15
This function also handles leading zeros correctly:
for i in range(16):
b = format(i, '05b')
n = binary_to_decimal(b)
print('{:2} {} -> {}'.format(i, b, n))
output
0 00000 -> 0
1 00001 -> 1
2 00010 -> 2
3 00011 -> 3
4 00100 -> 4
5 00101 -> 5
6 00110 -> 6
7 00111 -> 7
8 01000 -> 8
9 01001 -> 9
10 01010 -> 10
11 01011 -> 11
12 01100 -> 12
13 01101 -> 13
14 01110 -> 14
15 01111 -> 15
Actually, we don't even need that int
call, if we assume we only get passed valid strings:
def binary_to_decimal(bstring):
if not bstring:
return 0
return binary_to_decimal(bstring[:-1]) * 2 + (bstring[-1] == '1')
Upvotes: 3
Reputation: 56527
If you are trying to recursively parse a number (as an exercise) then have a look at this:
def parse_binary(binary_string, power):
if len(binary_string) == 0:
return 0
last_digit = int(binary_string[-1]) * (2**power)
return last_digit + parse_binary(binary_string[:-1], power+1)
def BinaryToDecimal(binary_string):
return parse_binary(binary_string, 0)
But if you want to do this efficiently then simply call int(binary_string, 2)
.
Upvotes: 0