Program that converts the Binary string to the Numeric

b=‘1111’

i=0

while b:

i = i*2+(ord(b[0])-ord(‘0’))

b=b[1:]

print(‘Decimal value’+ str(i)

Can anyone explain what does ord(b[0]) do here?

This is a great thing to play around with in the REPL - the Python command-line interpreter. Start by looking at it one piece at a time.

``````>>> b='1111'
>>> b[0]
'1'
>>> ord(b[0])
49
``````

So… what does ord() do? Let’s have a look at its documentation. (You can see this interactively by typing `help(ord)` - note that you aren’t calling ord here, you’re passing it as a parameter to the `help` function.)

``````Help on built-in function ord in module builtins:

ord(c, /)
Return the Unicode code point for a one-character string.
``````

Does that answer the question? If not, here’s a video from Computerphile about the basics of Unicode: https://www.youtube.com/watch?v=MijmeoH9LT4 What the ord() function does is take a character and give you its number; there’s a corresponding `chr()` function which takes a number and gives you back the character.

Hope that’s a start!

Hey Chris bro! Now i understood after reading this twice:
b=‘1111’

b[0]
‘1’
ord(b[0])
49

I learnt C++ so now i understood this shit lol thanks m g!

1 Like

Bro can you please tell me why we have used i*2?

This is part of the concept of place value - since you’re working in binary, each place is worth 10 (binary) or 2 (decimal) times the previous place. Try working through things manually and see it happen. If you were to multiply by 10 (decimal) instead, you would get the number represented by a string of decimal digits; if you were to multiply by 10 (octal) or 8 (decimal), you’d get the number represented by a string of octal digits; etcetera.

1 Like

Each time through the loop, what values do you see for `i` if you test it? Do you see how that relates to the `b` input?

Let’s say I have a value `i` that represents the converted result for `100`, and then I want to get the result for either `1000` or `1001` (both of the 4-bit binary strings starting with `100`). How will the result for `100` help us here? What steps would you take, in order to compute the rest of the result? Can you see why multiplying by 2 would be helpful? (Hint: what’s another name for “binary”?)

1 Like

As an aside, note that Python has the ability to do binary-decimal conversions inbuilt. `int()` accepts two parameters, with the second specifying the number base to use. `int("1111", 2) == 15`. Of course that doesn’t help with understanding how such a conversion actually works.

1 Like

Got it Spencer! Thanks!

This explanation was the best, Karl! Thanks a ton!