binary to octal Algorithm
The binary to octal algorithm is a process used to convert binary numbers, which are numbers expressed using only two digits (0 and 1), into octal numbers, which use a base 8 numbering system and are represented using digits from 0 to 7. This conversion is often used in digital systems, particularly in computer programming and electronic communications, as octal numbers are easier to read and work with than lengthy binary strings. The algorithm works by grouping binary digits in sets of three, starting from the least significant bit (LSB) or the rightmost digit, and then converting each group into its equivalent octal value.
To execute the binary to octal algorithm, first, the given binary number is divided into groups of three bits, starting from the rightmost digit. If the binary number is not a multiple of three, it is padded with zeros on the left side to form a complete group of three. Then, the algorithm calculates the octal digit for each group by multiplying the first binary digit of the group by 4, the second binary digit by 2, and the third binary digit by 1, and finally summing these values to obtain the octal digit. This process continues for all the groups, and the obtained octal digits are combined in the same order as the processed binary groups, resulting in the final octal representation of the binary number. The binary to octal algorithm is a simple and efficient method for converting binary numbers to their octal equivalent, which can be useful in various applications in computer science, mathematics, and other fields.
// Binary number to octal number conversion
#include<stdio.h>
//Function that returns the last three digits
int three_digits(int n)
{
int r, d = 0, p=1;
for(int i=0; i<3; i++)
{
r = n%10;
d += r * p;
p *= 10;
n /= 10;
}
return d;
}
int main(void)
{
int binary_num, d=0, base=1, remainder, td, res=0, ord=1;
printf("Enter the binary no: ");
scanf("%d", &binary_num);
while(binary_num > 0)
{
if(binary_num > 111) //Checking if binary number is greater than three digits
td = three_digits(binary_num);
else td = binary_num;
binary_num /= 1000;
d = 0, base =1;
// Converting the last three digits to decimal
while(td > 0)
{
remainder = td % 10;
td /= 10;
d += (base * remainder);
base *= 2;
}
res += d * ord; // Calculating the octal value
ord *= 10;
}
printf("\nOctal equivalent is: %d", res);
return 0;
}