Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read contents of a file as hex in C

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 ?

like image 976
vikkyhacks Avatar asked Sep 09 '13 08:09

vikkyhacks


1 Answers

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;
   }
like image 124
No Idea For Name Avatar answered Oct 13 '22 01:10

No Idea For Name