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
|Category||Requirements, Conventions or Software Version Used|
|System||Any Linux distro|
|Other||Privileged access to your Linux system as root or via the |
|Conventions|| # - requires given linux commands to be executed with root privileges either directly as a root user or by use of |
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
That's all there is to it. Now you will have an easy time converting binary numbers to decimal integers with Python.