Here is what i coded for a simple binary to octal converion. If no of digits in binary are multiple of 3 then it works fine but get crashed otherwise . . . . am not able to figure our how to pad up for the grouping of 3 when no of binary didgits are not multiple of 3.
Here is my code.
Please avoid validate(). It works fine.
Other solutions are most welcomed.
// Program for converting a binary into octal equivalent.
#include<stdio.h>
#include<conio.h>
#define MAX 1000
int validate(char *);
int main()
{
printf("\t* * * * * PROGRAM TO CONVERT BINARY INTO OCTAL NUMBER * * * * *");
char bin[MAX],oct[MAX];
int sum=0,re,i=0,o=0,k=1,j=1;
start:
printf("\n\nEnter a binary number: ");
gets(bin);
re=validate(bin);
if (re==1)
{
goto start;
}
else if(re==0)
{
goto end;
}
else if(re==2)
{
// ------- Conversion Begin.
while(bin[i]!='\0')
{
if(k<=3)
{
sum=sum+((((int)bin[i])-48)*j);
j=j*2;
k++;
i++;
if (k==4)
{
oct[o]=sum;
o++;
j=1;
sum=0;
k=1;
}
}
}
// ------- Conversion end ^^.
printf("\n\nThe octal equivalent is: ");
for(i=o-1; i>=0; i--)
{
printf("%d", oct[i]);
}
}
getch();
end:
return 0;
}
//---- Function for validation.
int validate(char bin[])
{
int i=0;
char ch;
while(bin[i])
{
if (bin[i]=='1' || bin[i]=='0')
{
// Do Nothing.
}
else
{
puts("\nYou entered an invalid binary number. \tDo you want to continue (y/n) ?");
ch=getchar();
getchar();
if (ch=='y' || ch=='Y')
{
return 1;
}
else
{
return 0;
}
}
i++;
}
return 2;
}
Thanx.