Binary to Octal Using List and Dictionaries Python

In this class, we write a program to convert binary to octal using list and dictionaries python.

For Complete YouTube Video: Click Here

Table of Contents

Binary to Octal

Q) Given a binary number in integer format. Display the equivalent octal number.

Example:

Given Input. 11100010110110

Output: 34266

Logic

Given a binary number, we have to partition three digits from left to right.

The first three digits are 110. this 110 is octal equivalent to 6.

Please take the next three digits. In our example, the digits are 110, which is octal equivalent to 6.

Repeat this three-bit partition till the right end.

To take the last three digits of the integer number, we have to divide the number by a thousand.

Divide by thousand and take the reminder value.

Take the next three digits, take the number obtained from the first division, and divide by a thousand. We get a second set of three digits.

Similar logic we discussed in our previous example. Click here.

How to convert the binary number to octal?

To do this conversion, we use two ways, one using a list and the other using dictionaries.

Here we understand the use of dictionaries.

In a list, we are taking all the octal values possible in binary.

Index will give octal value. At the index position binary value is placed.

list=[0,1,10,11,100,101,110,111]

At the index position zero, binary value zero is placed.

The one index position consists of a binary one. So on.

We use this list to convert binary to octal.

In the same way, we can mention the octal-binary pairs as key-value pairs in the dictionary.

But the use of a dictionary if we want to convert to hexadecimal number. We can mention the A, B..F values.

The list indexes are not possible to take hexadecimal values A,B..F.

Both the programs are shown below.

Program

Program using List

number=int(input("enter your binary number"))
 x=number
 octalnumbers=[0,1,10,11,100,101,110,111]
 output=[]
 while(x!=0):
     reminder=x%1000
     output.append(octalnumbers.index(reminder))
     x=x//1000
 output.reverse()
 print(output)

Program using dictionaries

number=int(input("enter your binary number"))
 x=number
 octalnumbers={0:0,1:1,10:2,11:3,100:4,101:5,110:6,111:7}
 output=[]
 while(x!=0):
     reminder=x%1000
     output.append(octalnumbers[reminder])
     x=x//1000
 output.reverse()
 print(output)