0

I want to write a function that takes a string of Binary and returns the result as Decimal.

I've written some code but if I didn't know it needed to be a string of Binary instead of just the numbers. Is there a way to change the code so it takes the string? I don't want to turn the binary to float, I want to turn it into decimal.

#Binary to Decimal
def bi_to_dec(binary):
  binary1 = binary 
  decimal, i, n = 0, 0, 0
  while(binary != 0): 
    dec = binary % 10
    decimal = decimal + dec * pow(2, i) 
    binary = binary//10
    i += 1
  return decimal  
KittyWhale
  • 89
  • 7
  • 1
    Does this answer your question? [How to convert a binary (string) into a float value?](https://stackoverflow.com/questions/8751653/how-to-convert-a-binary-string-into-a-float-value) – Nicolas Gervais Nov 01 '19 at 15:15
  • that's taking a string of binary and returning a float, but I want to return the decimal version of the string of binary. – KittyWhale Nov 01 '19 at 15:17
  • `sbi_to_dec = lambda s: bi_to_dec(int(s))` and off you go. – user2390182 Nov 01 '19 at 15:18

1 Answers1

1

I'm going to assume this is an exercise where you have to write the algorithm yourself. Otherwise, you should just use the built-in function int(binary, 2) to parse the string binary in base 2 as an int.

If binary is a string, then the parts of your code you need to change are those which get the individual bits from the string. You can iterate over the bits in the string by writing for bit in reversed(binary):. This gives you a variable bit which is the current bit as a string, and because you reversed the string you get the bits in order from least-significant to most-significant as your algorithm requires. From there, you can simply convert the bit to an int using dec = int(bit).

kaya3
  • 47,440
  • 4
  • 68
  • 97
  • Here's what I have now````def bi_to_dec(binary): for bit in reversed(binary): dec = int(bit) binary1 = dec decimal, i, n = 0, 0, 0 while(binary != 0): dec = binary1 % 10 decimal = decimal + dec * pow(2, i) binary = binary1//10 i += 1 return decimal ```` It works for 2/4 of the test cases, for 11 it turns it into 1 then it stays 1 through the whole thing. – KittyWhale Nov 01 '19 at 15:38
  • The `for` loop should be instead of your `while` loop. It doesn't make sense to write `while binary != 0` when `binary` is a string. – kaya3 Nov 01 '19 at 15:43