File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ #1 0 1 1 = 1*2^3 + 0*2^2 + 1*2^1 + 1*2^0
2+
3+ #length = 4
4+
5+ #binum[0] = 1
6+ #binum[1] = 0
7+ #binum[2] = 1
8+ #binum[3] = 1
9+
10+
11+ #Assign user entered value into a String binaryNumber
12+ binaryNumber = input ("Please enter a binary number to convert to Decimal Number" )
13+
14+ print (binaryNumber )
15+
16+ #Get the length of user entered binary Number and assign to a variable length
17+ length = len (binaryNumber )
18+
19+ #Start converting Right most Binary Number to Decimal Number and move towards Left
20+ #Start basePower = 0 and increment by 1 as you move from Right to Left
21+ #Keep appending the converted values to the result
22+ #Exit the Loop once you reach the Left most number in the Binary
23+
24+ decimalValue = 0
25+ basePower = 0
26+ #While the length is greater than 0
27+ while length > 0 :
28+ #binaryNumber = Start last element in the array binaryNumber[Length -1] and assign it to binaryNumber
29+ binaryElement = binaryNumber [length - 1 ]
30+
31+ #Make sure the user entered value does not contain anything other than 0 and 1
32+ if binaryElement != '1' and binaryElement != '0' :
33+ raise Exception ('Only 1 and 0 are allowed in Binary Number. User entered value contains {}' .format (binaryElement ))
34+
35+ #DeciValue = DeciValue + BiValue * 2**BasePower
36+ decimalValue = decimalValue + int (binaryElement ) * (2 ** basePower )
37+
38+ #BasePower = BasePower + 1
39+ basePower = basePower + 1
40+
41+ #Legth = Length - 1
42+ length = length - 1
43+
44+ print ('Decimal Value of binary number: ' + binaryNumber + ' = {}' .format (decimalValue ))
You can’t perform that action at this time.
0 commit comments