Binary to octal giving wrong result

• 04-10-2012
abhishekcoder
Binary to octal giving wrong result
Hi Guys,

I have written the below program to convert binary to octal, it is giving me erroneous results. On entering 1111 as the input number I should get 17 as the output, whereas I am getting 16707000337 as the output. Kindly help me out, below is my program:

Code:

```/*program to convert binary to octal*/ #include<math.h> #include<stdio.h> #include<stdlib.h> int main() {     int bin,dec[100]={0},i=0,j=0,k=0,num=0,output[100]={0},number=0,rem1,rem,output1;     printf("enter the binary number to be converted into octal");     scanf("%d",&bin);     rem1=bin; /*counts the number of digits in the input binary number*/     while(rem1!=0)     {             rem1=rem1/10;                num+=1;     } /*converts binary number to decimal */     for(i=0;i<num;i++)     {             number=bin%10;             bin=bin/10;             dec[i]=pow(2,j)*number;             j++;     } /*converts binary number to decimal */     for(;i>=0;i--)     {             output1+=dec[i];     } /*converts decimal to octal*/     while(output1!=0)     {                            rem=output1%8;                    output1=output1/8;             output[k]=rem;             k+=1;     } /*prints the value of octal*/     printf("the octal representation is");     for(;k>0;k--)     {             printf("%d",output[k-1]);     }     system("pause");     return 0; }```
Thank you.
• 04-10-2012
grumpy
Binary is base 2, not base 10. You are mixing that up.

The first loop counts the number of decimal (base 10) digits in rem1, not - despite what your comment says - the number of binary (base 2) digits.

In the second loop, number is the last decimal digit (each time through the loop) not a binary digit. dec[i] therefore gets the value of 2^i times that last decimal digit (where I'm using ^ as a shorthand to represent "to the power of").

So the third loop is summing up those dec[i]'s, and storing the result in output1. That is not a conversion of binary to decimal.

The fourth loop is extracting the octal digits (in reverse order) of output1 .... which, as I said, is not a decimal representation of the value you input.

The thing to remember is that the distinction between binary, octal, and decimal is not based on value. It is a manner of output. The value 10 (in decimal) will be 1010 in binary and will be 12 in octal. They are all the same value (when stored in an int). It is the manner of output that changes.
• 04-10-2012
Subsonics
Quote:

Originally Posted by grumpy
It is the manner of output that changes.

And with that said, printf has a %o format specifier to print in octal.