Learn about Binary to Octal in C using Function in the below code example. Also refer the comments in the code snippet to get a detailed view about what’s actually happening.
Binary to Octal in C using Function
Source code:
#include<stdio.h>
#include<math.h>
int convertBinaryToDecimal(int m);
int convertDecimalToOctal(int n);
int main()
{
int binary, decimal, octal;
printf("Enter Binary Number: ");
scanf("%d", &binary);
decimal = convertBinaryToDecimal( binary );
octal = convertDecimalToOctal( decimal );
printf("Octal Value= %d\n",octal);
return 0;
}
int convertBinaryToDecimal(int m)
{
int dec=0, i=0;
while(m != 0)
{
dec += (m%10) * pow(2,i);
m /= 10;
i++;
}
return dec;
}
int convertDecimalToOctal(int n)
{
int oct=0, i=1;
while(n != 0)
{
oct += (n%8) * i;
n /= 8;
i *= 10;
}
return oct;
}
Output:
Enter Binary Number: 1010
Octal Value= 12
Hope above code works for you and Refer the below Related Codes to gain more insights. Happy coding and come back again.
Similar Codes :
C Program to convert Binary to Octal
C Program to Convert Octal to Binary using function