I have to make a menu in my coding class. The user is able to choose a number on the menu and the menu is able to close. I have everything down except for binary to decimal. My code so far is shown below.
base10
is what I am working on. I just don't know the code to get to it since I had to miss class and he went over it in class.
#Name: Menu
#Input:
#Output:
#Description:
def menu():
while(True):
print("Welcome The Menu")
print("\t 1. Convert Binary to Decimal")
print("\t 2. Convert Decimal to Binary")
opt=input("Input a number or 9 to Quit. ")
if(int(opt)==1):
base10()
elif(int(opt)==2):
base2()
elif(int(opt)=="9"):
break;
else:
print("Invalid Input")
#Name: Reverse
#Input: String s
#Output: String r
#Description: This function takes a string as input and reverses that string
#returning it as output.
def reverse():
r=""
for i in s:
r=i + r
return r
#Name: Base 10
#Input:
#Output:
#Description
def base10():
num=int(input("Enter a binary number:"))
sum=0
for i in range(0,len()):
sum+=(int([i])*(2**i))
print(sum)
#Name: Base 2
#Input: num
#Output: b
#Description: It takes the number from the user and divides it by two. B is the binary number and num is the decimal number.
def base2():
b=""
num=int(input("Enter a decimal number: "))
while(num != 0):
b=str(num % 2) + b
num=num // 2
int(num == 10)
print(b)
menu()
The expected result is for me to enter a number in my menu to choose either binary to decimal or decimal to binary. Then I should be able to put in the base2
and base10
numbers and get the opposite back. (I cannot use bin!)
A binary representation of a (positive) integer can be viewed as a weighted sum.
Consider 1011
= 11.
1011 abcd In other words: a = c = d = 1 and: b = 0
Can be represented as a weighted sum:
8*a + 4*b + 2*c + 1*d
By plugging in a,b,c,d as defined you'll get 11, but another way to look at the weighted sum is:
(2**3)*a + (2**2)*b + (2**1)*c + (2**0)*d
or
(2**3)*a + (2**2)*b + (2**1)*c + (2**0)*d
└ exponent └ exponent └ exponent └ exponent
Here, 2 raised to a decreasing exponent, times the binary digit.
In other words:
(2**3)*1 + (2**2)*0 + (2**1)*1 + (2**0)*1 == 11
It might be easier to reverse the string first, then the exponent counts upwards from zero:
(2**0)*1 + (2**1)*1 + (2**2)*0 + (2**3)*1 == 11
Without giving too much away, assuming you had the binary string in a variable binstr
, I'd take a look at the output of:
print(list(enumerate(reversed(binstr))))
or
for (i, x) in enumerate(reversed(binstr)):
print(i, x)
One way might end up looking like:
intval = sum(<something> for (i,x) in enumerate(reversed(binstr)))
But that's not the only way. There are other ways, including using reduce
(or a similar approach).
Of course, there's always int(binstr, 2)
but I'm guessing that's not allowed either.
The int
constructor accepts an optional base. You can rewrite base10
as
def base10():
num = int(input("Enter a binary number:"), 2)
print(num )
Converting the other way would normally be done with bin
. Another way to do it is to check the bits of a number one by one. Your base2
implementation is close, but you shouldn't print in the loop.
Something like:
output = []
while num:
output.append(num % 2)
num //= 2
print(''.join(reversed(output)))
An alternative is to use the bit_length
method of int
along with a simple but twiddle to create the number in the correct order:
b = ''.join(str(int(bool(num & (1 << n)))) for n in range(num.bit_length() - 1, -1, -1))
The monstrosity str(int(bool(num & (1 << n))))
converts a bit flag that is a power of 2 into an boolean, and then uses the integer representation of the boolean to generate a string that is either 0
or 1
. It's equivalent to doing '1' if num & (1 << n) else '0'
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.