Here is my solution now. Finished it yesterday:
Code:
#include <stdio.h>
#include <stdlib.h> /* for allocating memory for the strings */
#define PUFFER 256
int lenof(char *str); /* returns the length of a string inclusive the ending '\0' */
void asctobin(void); /* converts ASCII-characters into binary digits */
void bintoasc(void); /* converts binary digits into ASCII characters */
unsigned char bin[]={1,2,4,8,16,32,64,128}; /* bitfield */
int main(void)
{
char chose;
for(chose=0;chose<50;chose++,printf("\n")) ; /* Clear screen */
again:
printf("Enter \'A\' to convert ASCII to binary or \'B\' to convert binary into ASCII: ");
scanf("%c",&chose);
if(chose=='A' || chose=='a') asctobin();
else
{
if(chose=='B' || chose=='b') bintoasc();
else{
rewind(stdin); /* back to the begin of stdin; if more then one character was entered */
goto again;} /* only accepts 'A','a','B' and 'b' as inputs */
}
return 0;
}
void asctobin(void)
{
char *string,c;
int count,len;
if((string=(char*)malloc(PUFFER))==NULL)
{
printf("Cannot allocate enough memory!");
exit(1); /* exit with the return code an error */
}
printf("Enter string (max length: 255 characters): ");
rewind(stdin); /* back to the begin of stdin */
fgets(string,PUFFER-1,stdin);
len=lenof(string);
for(;len>1;len--) /* as often as the value for the length of the inputed string */
{
c=*string; /* the character *string points to at the moment */
for(count=7;count>=0;count--)
{
if(c>=bin[count])
{
printf("1");
c-=bin[count];
}else
printf("0");
}
*string++;
printf(" ");
}
}
int lenof(char *str)
{
int count=0;
while(*str!='\0' && count<256)
{
*str++;
count++;
}
return(count);
}
void bintoasc(void)
{
char *string,c;
int count=0,len;
if((string=(char*)malloc(PUFFER))==NULL)
{
printf("Cannot allocate enough memory!");
exit(1); /* exit with the return code for an error */
}
printf("Enter digits (max 255):");
rewind(stdin); /* back to the begin of stdin */
fgets(string,PUFFER-1,stdin);
len=lenof(string);
for(;len>1;len--) /* as often as the value for the length of the inputed string */
{
if(*string=='1')
{
c+=bin[7-count];
count++;
}else
if(*string=='0') count++;
if(count%8==0)
{
printf("%c",c);
count=c=0;
}
*string++;
}
}
klausi