Contents
- binaryToDecimal2.py
- binaryToDecimal.py
binaryToDecimal2.py 1/2
[top][prev][next]
# Converts a binary number into a decimal
# By CSCI111
print("This program converts a binary number into a decimal number.")
# get the input as a string
binaryNum = input("Enter a binary number: ")
# TODO: error checking that binary number is all 0s and 1s
length = len(binaryNum)
decimalValue = 0
# go through the powers in the number (from left to right)
for power in range( length-1, -1, -1 ):
# figure out the position based on the power
pos = length - power - 1
# calculate the value of the bit
bit = int(binaryNum[pos])
decimalValue = 2**power*bit + decimalValue
print("The decimal value is", decimalValue)
binaryToDecimal.py 2/2
[top][prev][next]
# Converts a binary number into a decimal
# By CSCI111
print("This program converts a binary number into a decimal number.")
# get the input as a string
binaryNum = input("Enter a binary number: ")
# TODO: error checking that binary number is all 0s and 1s
decimalValue = 0
# go through the powers in the number (from right to left)
for power in range(len(binaryNum)):
# calculate the position of the bit with that power
pos = -(power+1)
# figure out if the bit is a one or zero
# multiply the bit by 2 to the power of the position
if binaryNum[pos] == "1":
decimalValue = 2**power + decimalValue
# The following is equivalent to the statements above
#bit = int(binaryNum[pos])
#decimalValue = 2**power*bit + decimalValue
print("The decimal value is", decimalValue)
Generated by GNU enscript 1.6.4.