Converting binary to decimal: It is not as hard as you think. Imagine a set arra
ID: 3567852 • Letter: C
Question
Converting binary to decimal:
It is not as hard as you think. Imagine a set array of numbers: 128,64,32,16,8,4,2,1. This array, or group, of numbers is built upon 'doubling.' Think of it as doubling. Starting with '1', doubling that yields '2', and then doubling that yields '4', then 8, then 16, etc. You the take a decimal (in this case less than 256), and follow this logic:
Start with a number, any number LESS than 256.
1. Is this number greater than or equal to 128? If it is, then subtract it from 128, then assig a '1.' If not, the move onto the 64, and assign a '0.'
2. Is this number greater than or equal to 64? If so, subtract it from 64, than assign a '1'. If not, assign a 0, then move on.
3. Complete until you reach the end Examples include: 140 = 10001100, 8 = 1000 The Problem:
So, in this problem, write a program in Python that takes a given number less than 256 in DECIMAL and converts it to BINARY
Explanation / Answer
print"=====================================================" print" DECIMAL TO BINARY AND BINARY TO DECIMAL CONVERSION" print"=====================================================" print" Enter 1 if you want to convert dec to bin" print" Enter 2 if you want to convert bin to dec" print"=====================================================" x=input("Enter your choice: ") if x==1: i=1 s=0 dec=input("Enter decimal to be converted: ") while dec>0: rem=dec%2 s=s+(i*rem) dec=dec/2 i=i*10 print "The binary of the given number is ",s,'.' else: bin=raw_input ('Enter binary to be converted: ') n=len(bin) res=0 for i in range(1,n+1): res=res+ int(bin[i-1])*2**(n-i) print "The decimal of the given binary is ",res,'.' print"=====================================================" raw_input()