48.1k views
5 votes
Write a Python program that translates a binary number of n bits to a decimal number. Your program should first ask the user the length of the binary number (how many bits). Using that information, ask the user to provide each bit from lowest to highest. Once the user has entered all the bit values for the binary number, report back the decimal value. Hint: You should use the mechanism to convert binary to decimal in earlier lectures. Note: Your program should not use any functions or methods from any library.

1 Answer

3 votes

Answer:

Follows are the code to this question:

n= int(input("please enter number of bits, which want to convert for binary to decimal numbers: "))

p= 1#defining variable p for calculate power

d= 0#defining variable d for calculate decimal value

for i in range(n):#defining for loop for input bits value

b= int(input("Enter the bit value from lowest to highest: "))#input value in b

if b==1:#defining if block that check input is 1 value

d=d+p#calculating decimal value

p=p* 2#calculating power

print("The converted decimal number is:",d)#print value

Output:

please find the attached file.

Step-by-step explanation:

In the above-given code, n variable is defined, which takes the number of bits value which you want to convert into a decimal value.

In the next step, "d and p" variable is defined that calculates the power and decimal number and store its value respectively, in this step, a for loop is used that uses the "b" variable for inputs bits value into lowest to the highest form, and use the if block.

In this block, it checks if the input value is one then it calculates its power and store its value into the "d" variable and use the print method to print its value.

Write a Python program that translates a binary number of n bits to a decimal number-example-1
User Keiter
by
5.3k points