I need to write a program that reads a binary file and writes the file to a text file in ASCII Hex format.
I also need each line to be 16 bytes long or 32 characters like this:
:100000002345a42d etc.
":" is start of new line
"10" is number of bytes converted (in this case 16)
"0000" is 16 bit address of the first byte (next line will be 0010)
"00" is page number (always 00 for this assignment)
NEXT 32 characters represent 16 binary bytes
AT the end there must be a check sum byte ( the 2's complement of all the bytes in the line without colon.
This is the program that I have written. I have problem inserting all the numbers before my 32 characters and also the check sum. Also the last line could have less than 16 bytes so I need to include that too. All the work has to be done in processFiles function.
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <string.h>
long int getFileSize(FILE *file);
void getFilenames(char inf[],char outf[]);
void processFiles(FILE *source,FILE *dest,long int fsize);
void convertToASCII(char ch,char *no1,char *no2);
char conv2Ascii(char no);
void main()
{
FILE *f1,*f2;
char infile[30],outfile[30];
long int fsize;
getFilenames(infile,outfile);
if (f1 = fopen(infile ,"rb"))
{
f2 = fopen(outfile ,"wb");
fsize=getFileSize(f1);
processFiles(f1,f2,fsize);
fclose(f1);
fclose(f2);
}
else
perror("outfile");
}
void getFilenames(char inf[],char outf[])
{
printf("Enter the binary file name :");
scanf("%s",inf);
printf("Enter the text file name :");
scanf("%s",outf);
}
void processFiles(FILE *source,FILE *dest,long int fsize)
{
long int i=0,count=0,j;
char buffer[61], a,b, input;
while (fsize>0)
{
input=getc(source);
{
convertToASCII(input,&a,&b);
buffer[i++]=a;
buffer[i++]=b;
count++;
if ((count%16) == 0)
{
i=0;
for(j=1; j<=32; j++)
fprintf(dest,"%c",buffer[j]);
fprintf(dest,"\n\0");
}
}
fsize--;
}
}
long int getFileSize(FILE *fptr)
{
long int size;
fseek(fptr,0L,SEEK_END);
size = ftell(fptr);
rewind(fptr);
return size;
}
void convertToASCII(char ch,char *no1,char *no2)
{
char a,b;
a=((ch>>4) & 0x0f);
b=(ch & 0x0f);
*no1=conv2Ascii(a);
*no2=conv2Ascii(b);
}
char conv2Ascii(char no)
{
if (no<=9)
no = no+'0';
else
no = no-10+'A';
return no;
}