C Program to Convert Binary Number to Octal Number

Write a C program to convert binary to octal. Write a C program to convert binary number into its octal equivalent. The C program given below and accepts a binary number from user and uses while loop construct to convert binary number to octal number.
/* C Program to Convert Binary Number to Octal */

#include <stdio.h>

int main()
{
 long int binarynum, octalnum = 0, j = 1, remainder;
 
 printf("Enter the value for  binary number: ");
 scanf("%ld", &binarynum);

 while (binarynum != 0)
 {
  remainder = binarynum % 10;
  octalnum = octalnum + remainder * j;
  j = j * 2;
  binarynum = binarynum / 10;
 }

 printf("Equivalent octal value: %lo", octalnum);

  return 0;
}

Output:

Enter the value for  binary number: 10101
Equivalent octal value: 25

Comments