Read contents of a file as hex in C

vikkyhacks picture vikkyhacks · Sep 9, 2013 · Viewed 35.1k times · Source

I have a file with hex values saved as hex.txt which has

9d ff d5 3c 06 7c 0a

Now I need to convert it to a character array as

unsigned char hex[] = {0x9d,0xff,0xd5,0x3c,0x06,0x7c,0x0a}

How do I do it ?

Answer

No Idea For Name picture No Idea For Name · Sep 9, 2013

use a file read example like from here and with this code read the values:

#include <stdio.h>   /* required for file operations */
#include <conio.h>  /* for clrscr */

FILE *fr;            /* declare the file pointer */

main()

{
   clrscr();

   fr = fopen ("elapsed.dta", "rt");  /* open the file for reading */
   /* elapsed.dta is the name of the file */
   /* "rt" means open the file for reading text */
   char c;
   while(c = fgetc(fr)  != EOF)
   {
      int val = getVal(c) * 16 + getVal(fgetc(fr));
      printf("current number - %d\n", val);
   }
   fclose(fr);  /* close the file prior to exiting the routine */
}

along with using this function:

   int getVal(char c)
   {
       int rtVal = 0;

       if(c >= '0' && c <= '9')
       {
           rtVal = c - '0';
       }
       else
       {
           rtVal = c - 'a' + 10;
       }

       return rtVal;
   }