[Tutor] Binary to Decimal conversion
bgailer at gmail.com
Tue Mar 10 01:50:47 CET 2009
Chris Castillo wrote:
> I am having some difficulties in producing the correct code for a
> simple binary to decimal conversion program. The arithmetic I want to
> use is the doubling method - so if I wanted to get the decimal
> equivalent of 1001, I would start with multiplying 0 * 2 and adding
> the left most digit. I would then take the sum of 1 and multiply it by
> 2 and add the next digit to that product and so on and so forth until
> I come to an end sum of 9.
> I seem to come up with something like this:
> binnum = raw_input("Please enter a binary number: ")
> for i in range(0, len(binum), 1):
> item = "0"
> if i < len(binum) - 1:
> item = binum[i + 1]
> binsum = binsum * int(item) * 2 + binsum + int(binum[i])
> print "\nThe binary number ", binum, " you entered converts to",
> binsum, " in decimal."
Having said that I will point out
1 - to access elements of a sequence you may write:
for item in binnum:
2 - the first element of binnum is binnum. Your code starts by
accessing the 2nd element.
3- you use binsum before assigning anything to it. That is bound to
raise a Name error.
4 - I don't understand binsum = binsum * int(item) * 2 + binsum +
That does not agree with your verbal algorithm.
Chapel Hill NC
More information about the Tutor