Home »
Python
Input a number in binary format in Python
Python | Binary Input: Here, we are going to learn how to Input a number in binary format in Python programming language?
Submitted by IncludeHelp, on April 27, 2020
Syntax to convert binary value to an integer (decimal format),
int(bin_value, 2)
Here,
- bin_value should contain the valid binary value
- 2 is the base value of the binary number system
Note: bin_value must contain only binary digits (0 and 1), if it contains other than these digits a "ValueError" will return.
Program to convert given binary value to integer (decimal)
# function to convert given binary Value
# to an integer (decimal number)
def BinToDec(value):
try:
return int(value, 2)
except ValueError:
return "Invalid binary Value"
# Main code
input1 = "11110000"
input2 = "10101010"
input3 = "11111111"
input4 = "000000"
input5 = "012"
print(input1, "as decimal: ", BinToDec(input1))
print(input2, "as decimal: ", BinToDec(input2))
print(input3, "as decimal: ", BinToDec(input3))
print(input4, "as decimal: ", BinToDec(input4))
print(input5, "as decimal: ", BinToDec(input5))
Output
11110000 as decimal: 240
10101010 as decimal: 170
11111111 as decimal: 255
000000 as decimal: 0
012 as decimal: Invalid binary Value
Now, we are going to implement the program – that will take input the number as an binary number and printing it in the decimal format.
Program to input a number in binary format
# input number in binary format and
# converting it into decimal format
try:
num = int(input("Input binary value: "), 2)
print("num (decimal format):", num)
print("num (binary format):", bin(num))
except ValueError:
print("Please input only binary value...")
Output
RUN 1:
Input binary value: 11110000
num (decimal format): 240
num (binary format): 0b11110000
RUN 2:
Input binary value: 101010101010
num (decimal format): 2730
num (binary format): 0b101010101010
RUN 3:
Input binary value: 1111111111111111
num (decimal format): 65535
num (binary format): 0b1111111111111111
RUN 4:
Input binary value: 0000000
num (decimal format): 0
num (binary format): 0b0
RUN 5:
Input binary value: 012
Please input only binary value...
Python Tutorial
ADVERTISEMENT
ADVERTISEMENT