Python program to convert a binary number to its equivalent decimal, octal and hexadecimal equivalent.














































Python program to convert a binary number to its equivalent decimal, octal and hexadecimal equivalent.



Description:

This python program involves the conversion of a binary number system to its equivalent decimaloctal or hexadecimal number. This program makes use of f-strings in Python 3.6. The
binary numbering system has a base of 2 (MOD-2) and uses only two digits a '0' and '1' to represent a binary number value.  This program strictly makes sure that user must enter a valid binary number by using exceptional handling. The user can perform these conversions as many times as he wants.  Total execution time is also shown when the computation is successfully completed.


Program:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import time


class BinaryConv:

def __init__(self, num):
self.x = num

#Binary to decimal
def bin_to_dec(self):
return int(self.x, 2)

#Binary to octal
def bin_to_oct(self):
return oct(int(self.x, 2))[2:]

#Binary to hexadecimal
def bin_to_hex(self):
return (hex(int(self.x, 2))).upper()[2:]

def compute(self, x):
choices = {1 : self.bin_to_dec(), 2 : self.bin_to_oct(), 3 : self.bin_to_hex()}
return choices.get(x, 'Invalid Key. Try again')


def main():

flag = True
while flag:

print("Enter a binary number : ")
x = input()

while True:
try:
if False in [f == '0' or f == '1' for f in x]:
raise ValueError
except ValueError:
print('\nPlease make sure your number contains digits 0-1 only.')
print("Enter a valid binary number : ")
x = input()
else:
break

obj = BinaryConv(str(x))

print("\nEnter your choice : ")
print("1. Binary to decimal ")
print("2. Binary to octal ")
print("3. Binary to hexadecimal\n")

choice = int(input())

if 1 <= choice <= 3:
t0 = time.time()
res = obj.compute(choice)
t1 = time.time()
res_show = {1 : f'Decimal equivalent is {res}', 2 : f'Octal equivalent is : {res}', 3 : f'Hexadecimal equivalent is : {res}'}
print(res_show[choice])
total = t1 - t0
print(f"Computed successfully in {total:7.7f} seconds.")

print("\nWant to repeat? (yes/no) \n")
if input().lower() == 'yes':
flag = True
else:
flag = False


if __name__ == '__main__':
main()

Output:

Enter a binary number : 
10001023100

Please make sure your number contains digits 0-1 only.
Enter a binary number : 
1000111101101

Enter your choice : 
1. Binary to decimal 
2. Binary to octal  
3. Binary to hexadecimal

1
Decimal equivalent is : 4589
Computed successfully in 0.0001509 seconds.

Want to repeat? (yes/no) 
yes

Enter a binary number : 
1000111101101

Enter your choice : 
1. Binary to decimal 
2. Binary to octal  
3. Binary to hexadecimal

2
Octal equivalent is : 10755
Computed successfully in 0.0001574 seconds.

Want to repeat? (yes/no) 
yes

Enter a binary number : 
1000111101101

Enter your choice : 
1. Binary to decimal 
2. Binary to octal  
3. Binary to hexadecimal

3
Hexadecimal equivalent is : 11ED
Computed successfully in 0.0000355 seconds.

Want to repeat? (yes/no) 
yes

Enter a binary number : 
10010010101

Enter your choice : 
1. Binary to decimal 
2. Binary to octal  
3. Binary to hexadecimal
5

Invalid Key. Try again

Want to repeat? (yes/no) 
no


Sample Test Cases : 

This part of the article involves actual testing of our code using Python's unittest module. This is a really crucial part of any big project. Good tests make sure that change in a segment of our code doesn't affect the performance of other segments. Debugging of code becomes super-easy because of testing. This could be done as written below:

 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
import unittest
from binary_class import BinaryConv


class TestConversion(unittest.TestCase):

def setUp(self):
# Some sample large binary numbers for testing purposes
self.x1 = BinaryConv('10010100101010010101010')
self.x2 = BinaryConv('101110010101111111000001010')
self.x3 = BinaryConv('1001111110000011111110')
self.x4 = BinaryConv('1111110101010100001111110')

def test_bin_to_dec(self):
self.assertEqual(self.x1.bin_to_dec(), 4871338)
self.assertEqual(self.x2.bin_to_dec(), 97189386)
self.assertEqual(self.x3.bin_to_dec(), 2613502)
self.assertEqual(self.x4.bin_to_dec(), 33204350)

def test_bin_to_oct(self):
self.assertEqual(self.x1.bin_to_oct(), '22452252')
self.assertEqual(self.x2.bin_to_oct(), '562577012')
self.assertEqual(self.x3.bin_to_oct(), '11760376')
self.assertEqual(self.x4.bin_to_oct(), '176524176')

def test_bin_to_hex(self):
self.assertEqual(self.x1.bin_to_hex(), '4A54AA')
self.assertEqual(self.x2.bin_to_hex(), '5CAFE0A')
self.assertEqual(self.x3.bin_to_hex(), '27E0FE')
self.assertEqual(self.x4.bin_to_hex(), '1FAA87E')


if __name__ == '__main__':
unittest.main()

Output:

...
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK

Here ... means that all the 3 test cases have passed successfully. If anyone among them had failed, the failure of test case would be denoted by 'F'.

More Articles of Apoorv Patne:

Name Views Likes
Python program to count number of spaces in a file 1195 16
Python program to check whether all leaves of a binary tree are at same level 874 20
Python program to print unique words from a file 2912 15
Python program to find mirror image of a tree using recursive and iterative approach 1180 23
Python program to understand deletion in Red-Black Trees 4900 18
Usage of dictionaries in python 1491 28
Python program to work on binary trees using binarytree module 1301 12
Python program to write to a file 892 20
Python program to demonstrate usage of config-reader framework using configparser module 1233 17
Python program to create tree from given in order and pre order traversal 868 18
Python program to convert Sorted Array to binary search tree 1292 13
Python program to find the level-order traversal for a given binary tree 1294 21
Python program to remove punctuations from a given string. 914 21
Python program to find the minimum depth of a binary tree 1086 25
Python program to merge files 1301 20
Python program to find in-order predecessor and successor with and without recursion 3308 12
Python program to shuffle lines in a file 2522 19
Python program to encrypt a password using encryption 1232 18
Python program to compare strings 1136 29
Python send mail via command line argument 878 19
Python program to elaborate and understand memory management 1159 21
Python article to demonstrate the usage of help() and dir() methods 1206 19
Tset 841 13
Python program to construct a complete binary tree from a given array 4553 23
Python program to encrypt and decrypt contents from a file via command line 1981 24
Python program to count number of lines using different methods 865 19
Python program to perform copy, concatenation and reverse operations on strings 831 20
Python program to find maximum number using ternary operations 946 17
Python program to find the mirror of a given node in a binary tree 1008 17
Python program to convert decimal to its binary, octal and hexadecimal equivalent 985 27
Python program to extract and create a 7z file 3240 18
Python program to find all paths from root to leaves 1431 24
Python program to compute HCF and LCM of given numbers 1263 26
Python program to read a fiel 890 19
Python program to find size of tree with and without recursion 939 15
Python program to sort an integer array using quick sort, radix sort, merge sort, bucket sort and other algorithms 1097 16
Python birthday reminder application using SMTP and SQLAlchemy 3505 23
Python program to append content of one text file to another 1479 13
Python program to convert a binary number to its equivalent decimal, octal and hexadecimal equivalent. 1225 23
Python program to understand Red-Black trees and insert nodes to it 3524 23
Python program to understand linked lists and its operations (fully tested) 1093 12
Python program to check if two strings are a rotation of each other 1046 14

Comments