Input an integer containing 0s and 1s (i.e., a “binary” integer) and print its decimal equivalent. Appendix C, Number Systems, discusses the binary number system. (Hint: Use the mod- ulus and division operators to pick off the “binary” number’s digits one at a time from right to left. Just as in the decimal number system, where the rightmost digit has the positional value 1 and the

next digit leftward has the positional value 10, then 100, then 1000, etc., in the binary number system, the rightmost digit has a positional value 1, the next digit leftward has the positional value 2, then 4, then 8, etc. Thus, the decimal number 234 can be interpreted as 2 * 100 + 3 * 10 + 4 * 1. The decimal equivalent of binary 1101 is 1 * 8 + 1 * 4 + 0 * 2 + 1 * 1.)

What will be an ideal response?

```
# Converts a binary number into its decimal equivalent.

binaryNumber = raw_input( "Please enter a binary number: " )
binaryNumber = int( binaryNumber )

decimalValue = 0 # holds the decimal value
digitPosition = 0 # position in binary number

while binaryNumber > 0:

# isolate current last digit
lastDigit = binaryNumber % 10
binaryNumber = binaryNumber / 10

# calculate value of position if
# the last digit is not equal to zero
if lastDigit != 0:
counter = 0

# value of position in binary number
positionValue = 2 ** digitPosition

# update value of binary digit
decimalValue += lastDigit * positionValue

# move to next digit position
digitPosition += 1

# print decimal value of binary input
print "Decimal Equivalent is " + str( decimalValue )
```
Please enter a binary number: 1000
Decimal Equivalent is 8
Please enter a binary number: 1101
Decimal Equivalent is 13
Please enter a binary number: 01011
Decimal Equivalent is 11

Computer Science & Information Technology

You might also like to view...

An RSS file is written in _____.

A. SGML B. HTML C. XML D. AML

Computer Science & Information Technology

What is the worst case performance of the Knuth-Morris-Pratt algorithm?

a. O(n) b. O(n log n) c. O(n^2) d. O(1)

Computer Science & Information Technology