Read contents of a file as hex in C

前端 未结 4 428
孤独总比滥情好
孤独总比滥情好 2020-12-17 01:38

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

4条回答
  •  余生分开走
    2020-12-17 02:23

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

    #include    /* required for file operations */
    #include   /* 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;
       }
    

提交回复
热议问题