Input a number in binary format in Python

Python | Binary Input: In this tutorial, we will learn how to Input a number in binary format in Python programming language? Submitted by IncludeHelp Last updated : December 17, 2023

Prerequisite

Input a number in binary format

To input a number in binary format, use the input() method inside the int() method by passing the base value 2 which is used for converting binary numbers to decimals. This technique allows one to take input an input in binary format and then convert it into decimal format.

Syntax

Below is the syntax to take input in binary format:

variable = int(input("Message"), 2)

Python program to input a number in binary format

In this example, we are going to implement the program – that will take input the number as an binary number and printing it in the decimal 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...

Converting a decimal input to binary format

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

Python Tutorial

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.