Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Im trying to write a C program that will read an input text file by character, a

ID: 3668670 • Letter: I

Question

Im trying to write a C program that will read an input text file by character, and convert every character into Ascii equvalent, then convert ascii equvalent to binary.

I have the first part completed. This code will take in a text file named "input.txt", read it by char and convert each char to ascii.

Now i need to be able to convert each element of ascii array to binary. The code must also be able to referance to a specific element of the ascii array and convert w/e value is stored in there to binary.

#include <stdio.h>
#include <stdlib.h>

int main()
{
   FILE *fpointer;
   fpointer = fopen("input.txt", "r");
   char singlechar[150];
   int i = 0;
   int newch = 0;

   while (!feof(fpointer)){
       fgets(singlechar, 150, fpointer);
       puts(singlechar);
   }

   printf("ASCII values of each characters: ");
   while (singlechar[i]) {
       printf("%d ", singlechar[i++]);
   }

   fclose(fpointer);
   system("pause");
   return 0;
   }

Here is the output of my current code:

i want to be able to say singlechar[3] -> binary; and get the binary equvalent of 76

HELLO ASCII values of each characters 72 69 76 76 79 Press any key to continue .. .

Explanation / Answer

There are totally 128 well defined ascii charecters available.

so representing them in binary means, you need binary representation of numbers between 0 to 127.

You have not mention about your int size, so i assume it for 32 bit.so the binary representaion would be 32 bit.

#include <stdio.h>
#include <stdlib.h>

int main()
{
   FILE *fpointer;

int i = 0;

char binaryRep[33];

int j,k,n;
   fpointer = fopen("input.txt", "r");
   char singlechar[150];
   int i = 0;
   int newch = 0;

   while (!feof(fpointer)){
       fgets(singlechar, 150, fpointer);
       puts(singlechar);
   }

   printf("ASCII values of each characters: ");
  

while (singlechar[i]) {
printf("%d --> ", singlechar[i]);
n = singlechar[i];
for (i = 31,j=0; i >= 0; i--,j++)
{
k = n >> i;

if (k & 1)
binaryRep[j] = '1';
else
binaryRep[j] = '0';
}
binaryRep[32] = '';
printf("%s ",binaryRep);
}

   fclose(fpointer);
   system("pause");
   return 0;
   }