In this guide, we will show you a short script that can be used to convert a binary number to a decimal number in Python on Linux. This script uses casting which is used to convert a variable from one type to another. In this case, we use Python casting to convert a string to decimal number that is an integer.

Check out the script below to use it on your own system.

In this tutorial you will learn:
  • How to convert binary number to decimal with Python
Converting a binary number to decimal via Python script in Linux
Converting a binary number to decimal via Python script in Linux
Software Requirements and Linux Command Line Conventions
Category Requirements, Conventions or Software Version Used
System Any Linux distro
Software Python
Other Privileged access to your Linux system as root or via the sudo command.
Conventions # - requires given linux commands to be executed with root privileges either directly as a root user or by use of sudo command
$ - requires given linux commands to be executed as a regular non-privileged user

Python Script


SUBSCRIBE TO NEWSLETTER
Subscribe to our NEWSLETTER and receive latest Linux news, jobs, career advice and tutorials.


When you attempt to use casting to convert a variable type to integer, make sure that your variable input type is a string.

Without further ado, here is the Python script. Copy and paste the section below into a new file on your computer.

#!/usr/bin/env python

while True:
    try:
        # Try to convert bunary to decimal
        decimal_num = int(raw_input("Enter a binary number: "), 2)
        # If we fail we ask again user to enter binary number
    except ValueError:
        print "Your input is not a binary number! Please try again."
    else:
        # Exit program if the conversion from binary to decimal was successful
        break
# print converted decimal number
print decimal_num

Save your script, for example with name binary2decimal.py, then make it executable and run the script:

$ chmod +x binary2decimal.py
$ ./binary2decimal.py
Converting a binary number to decimal via Python script in Linux
Converting a binary number to decimal via Python script in Linux


That's all there is to it. Now you will have an easy time converting binary numbers to decimal integers with Python.

FIND LATEST LINUX JOBS on LinuxCareers.com
Submit your RESUME, create a JOB ALERT.
LINUX CAREER NEWSLETTER
Subscribe to NEWSLETTER and receive latest news, jobs, career advice and tutorials.
DO YOU NEED ADDITIONAL HELP?
Get extra help by visiting our LINUX FORUM or simply use comments below.