Project Four Solution
Below is a possible solution for the project :
/* MCS 260 Project 4 : converting characters into bit sequences */
#include<stdio.h>
int read_byte ( void );
/* reads 8 bits from standard output and returns the value,
returns -1 if '>' or EOF is reached */
void print_byte ( int n );
/* writes the binary representation of a number between 0 and 255 */
int main ( void )
{
int n, c = getchar();
if (c == '<')
{
printf("\"");
while ((n = read_byte())!= -1) printf("%c",n);
printf("\"");
}
else
{
printf("<");
while ((c = getchar())!= '"') print_byte(c);
printf(">");
}
return 0;
}
int read_byte ( void )
{
int bit,i,n = 0;
for (i = 0; i < 8; i++)
{
bit = getchar();
if ((bit == '>')||(bit == EOF)) return -1;
n = 2*n + (bit - '0');
}
return n;
}
void print_byte ( int n )
{
int i,val = 128;
int nb = n;
for (i = 8; i > 0; i--,val /= 2)
{
if (nb < val)
putchar('0');
else
{
putchar('1');
nb -= val;
}
}
}