Reputation: 25
I am currently making a python program that is byte adder related, it will prompt the user to enter 2 integers, add them together and if it's within the range of the actual size of a byte (0 to 255) display that number and also give the corresponding value in its 8 bit binary form, for example, the calculation is equal to 1, show the binary number which python declares as the correct one.
This is the task that I am doing ~
"The program must check the input data for the data type permitted and the data value limitations (the value of the integer must not exceed the actual size of byte-coded integers, i.e. min 00000000 and max 11111111 in Base 2 or min 0 and max 255 in Base 10 for positive integers" Input in both binary and decimal format with conversion to binary
def add():
Num1 = int(input("Input the first number between 0 and 255, the calculated answer must not be above 255: "))
Num2 = int(input("Input the second number between 0 and 255, the calculated answer must not be above 255: "))
calculatedanswer = Num1+Num2
if calculatedanswer >= 0 and calculatedanswer <=255:
print("The answer in decimal is" ,calculatedanswer,)
**bin(calculatedanswer)**
elif calculatedanswer < 0 and calculatedanswer >255:
print("Please ensure the added numbers are above 0 and below 255")
add()
This is my code so far, I have no trouble getting it to display the standard decimal number, but I really can't get the bin(calculatedanswer)
to show the binary equivalent of it. I tried using this method that I found on YouTube.
I think my main problem here is my lack of understanding of how "bin" works on python as this is really the first time I am using it.
I have put asterisks around the line that I am having trouble with.
Upvotes: 2
Views: 30233
Reputation: 177461
You do have to print the value:
>>> print(bin(160)) # This version gives the 0b prefix for binary numbers.
0b10100000
>>> print(format(160,'08b')) # This specifies leading 0, 8 digits, binary.
10100000
>>> print('{:08b}'.format(160)) # Another way to format.
10100000
>>> print(f'{160:08b}') # Python 3.6+ new f-string format.
10100000
Upvotes: 14
Reputation: 6441
One option for printing it would be to slice off the 0b
portion of the result, which I assume is what you mean when you say you are having problems with the bin
function.
Try this:
print(bin(calculatedanswer)[2:]))
Upvotes: 1