Binary String To Decimal Integer Converter
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 bina
Solution 1:
It looks like you haven't implemented the loop:
defbinaryToDenary():
Answer = 0
Column = 8whilenot Column < 1:
Bit = int(input("Enter bit value: "))
Answer = Answer + (Column * Bit)
Column = Column/2print("The decimal value is: {}".format(Answer))
Solution 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 inenumerate(arg))
Solution 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.
definteger_from_binary_input():
answer = 0
column = 8whileTrue:
bit_chars = raw_input("Enter bit value:")
assertlen(bit_chars) == 1assert bit_chars in"01"
bit = int(bit_chars)
answer = answer + column * bit
column /= 2if column < 1:
breakprint"Decimal value is: %d" % answer
return answer
output = integer_from_binary_input()
Post a Comment for "Binary String To Decimal Integer Converter"