Contents

  1. binaryToDecimal.wfunc.py

binaryToDecimal.wfunc.py

# Convert binary numbers to decimal numbers
# CS111

import sys

def main():
    
    print 
    print "This program converts binary numbers to decimal numbers."
    print
    
    binary_string = raw_input("Enter a number in binary: ")
    
    if not isBinary(binary_string):
        print "That is not a binary string"
        sys.exit()

    print "The decimal value is", binaryToDecimal(binary_string)

# returns True iff the string is binary (contains only 0s or 1s)
def isBinary(string):
    if not string.isdigit() :
        return False

    for bit in string:
        if bit != "0" and bit != "1":
            return False
    
    return True

# Given a binary string, returns the decimal value of that binary string.
def binaryToDecimal(bin_string):
    exponent = len(bin_string)-1
    
    dec_value = 0
    
    # for each bit in the binary string,
    # multiply the bit by 2 to the appropriate power
    # and add that to the decimal value, dec_value
    for bit in bin_string:
        bit = int(bit)
        #print bit,"* 2^%d" % exponent
        dec_value += bit * (2 ** exponent)
    
        exponent -= 1
   
    return dec_value
    
main()

Generated by GNU enscript 1.6.4.