问题
I am trying to write a program that converts a 4-bit string representation of binary into a decimal (base 10) integer.
This is what I got so far, but after I type In the 4-bit binary (e.g. 1101) It just comes out with: '>>>'.
Here is the flow diagram I am following:

Here is my code:
def binaryToDenary():
Answer = 0
Column = 8
Bit = int(input("Enter bit value: "))
if Column >1:
Answer = Answer + (Column * Bit)
Column = Column/2
elif Column <1:
print("The decimal value is: " + Answer)
binaryToDenary()
What am I doing wrong? Any hints?
回答1:
It looks like you haven't implemented the loop:
def binaryToDenary():
Answer = 0
Column = 8
while not Column < 1:
Bit = int(input("Enter bit value: "))
Answer = Answer + (Column * Bit)
Column = Column/2
print("The decimal value is: {}".format(Answer))
回答2:
You can use built-in methods or you can make your own function like so:
bintodec = lambda arg: sum(int(j) * 2**(len(arg) - i - 1) for i, j in enumerate(arg))
回答3:
Try this. This is a direct translation from the diagram. Note that in production code and real libraries, this is not a particularly useful function and is only useful as an examination exercise.
def integer_from_binary_input():
answer = 0
column = 8
while True:
bit_chars = raw_input("Enter bit value:")
assert len(bit_chars) == 1
assert bit_chars in "01"
bit = int(bit_chars)
answer = answer + column * bit
column /= 2
if column < 1:
break
print "Decimal value is: %d" % answer
return answer
output = integer_from_binary_input()
来源:https://stackoverflow.com/questions/29578704/binary-string-to-decimal-integer-converter