Algorithm and flowchart to perform binary to octal conversion

[206 views]

What is Binary Number System:

A number system with a base 2 is known as binary number system. Hence, binary numbers are denoted with a base 2. It consists of two values: 0 and 1. Each digit in this system is said to be a bit.
For example: (001101)2, (10001101)2, (11100)2, (10)2, etc.

What is Octal Number System:

A number system with a base 8 is known as octal number system. Hence, octal numbers are denoted with a base 8. It consists of the values: 0,1,2,3,4,5,6,7.
For example: (145)8, (36)8, (120)8, (4105)8, etc.

Let us take a look at the algorithm and flowchart to convert a binary number to its octal equivalent.

Algorithm to perform binary to octal conversion:

Step 1: Start Step 2: Read the binary number from the user, say ‘n’ Step 3: Initialize the decimal number, d=0 Step 4: Initialize the octal number, octal=0 Step 5: Initialize i=0 Step 6: Repeat while n != 0: Step 6.1: Extract the last digit by: remainder = n % 10 Step 6.2: n = n/10 Step 6.3: d = d + (remainder * 2i) Step 6.4: Increment i by 1 Step 7: Initialize i=1 Step 8: Repeat while d != 0: Step 8.1: Extract the remainder by: remainder = d % 8 Step 8.2: octal = octal+ (remainder * i) Step 8.3: d = d/8 Step 8.4: i = i * 10 Step 9: Display the octal number Step 10: Stop

Explanation:

There are many ways to convert a binary number to its octal equivalent. Here, to perform the conversion, we will first convert the binary number into decimal number system, and then change that decimal number to its octal equivalent.

We begin by taking the binary number as input from the user. We will first convert this number into decimal. To do so, we first initialize the decimal number, say ‘d’ as zero, and the octal number, say ‘octal’ as zero. To convert the binary number to decimal, we extract the last digit from the binary number one at a time and multiply it with 2 to the power of the number’s position. We repeat this process for all the digits of the number and then this product is added to get the decimal number.

Once we have the decimal number, we convert this into octal number system. To do this conversion, we divide the decimal number by 8 until zero is obtained. The remainder becomes the most significant bit of the octal number in each division.

To perform this conversion, we start a loop that runs until ‘d’ is equal to zero. We extract that remainder with the help of the modulus operator. After that, the remainder is multiplied by the place (starting from ones) in the octal number. We use a variable ‘i’ to keep track of the place where the next remainder is to be inserted. This variable is incremented after each loop iteration. Once the loop stops execution, we display the octal number.