C语言 在C中以十六进制读取文件的内容

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18693841/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:24:01  来源:igfitidea点击:

Read contents of a file as hex in C

chexfile-handling

提问by vikkyhacks

I have a file with hex values saved as hex.txtwhich has

我有一个十六进制值的文件保存为hex.txt具有

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 ?

我该怎么做 ?

采纳答案by vikkyhacks

This code does the job !!!, but requires us to initialize the size of the hex to be converted with #define FILELEN 15

这段代码完成了工作!!!,但需要我们初始化要转换的十六进制的大小 #define FILELEN 15

#include<stdio.h>

#define FILELEN 15

int ascii_to_hex(char c)
{
        int num = (int) c;
        if(num < 58 && num > 47)
        {
                return num - 48; 
        }
        if(num < 103 && num > 96)
        {
                return num - 87;
        }
        return num;
}

int main()
{
        FILE *fp = fopen("sample","r");
        unsigned char c1,c2;
        int i=0;
        unsigned char sum,final_hex[FILELEN/2];
        for(i=0;i<FILELEN/2;i++)
        {
                c1 = ascii_to_hex(fgetc(fp));
                c2 = ascii_to_hex(fgetc(fp));
                sum = c1<<4 | c2;
                final_hex[i] = sum;
                printf("%02x ",sum);
        }
        printf("\n");
}

回答by No Idea For Name

use a file read example like from hereand 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;
   }

回答by chux - Reinstate Monica

Perform 2 passes through the file.
1 Scan and count the required bytes.
2 Allocate needed memory, then repeat scan, this time saving the results.

执行 2 次遍历文件。
1 扫描并计算所需的字节数。
2 分配需要的内存,然后重复扫描,这次保存结果。

size_t ReadHexFile(FILE *inf, unsigned char *dest) {
  size_t count = 0;
  int n;
  if (dest == NULL) {
    unsigned char OneByte;
    while ((n = fscanf(inf, "%hhx", &OneByte)) == 1 ) {
      count++;
    }
  }
  else {
    while ((n = fscanf(inf, "%hhx", dest)) == 1 ) {
      dest++;
    }
  }
  if (n != EOF) {
    ;  // handle syntax error
  }
  return count;
}

#include <stdio.h>
int main() {
  FILE *inf = fopen("hex.txt", "rt");
  size_t n = ReadHexFile(inf, NULL);
  rewind(inf);
  unsigned char *hex = malloc(n);
  ReadHexFile(inf, hex);
  // do somehting with hex
  fclose(inf);
  free(hex);
  return 0;
 }

回答by Aneri

I can offer a code like this. Add proper includes.

我可以提供这样的代码。添加适当的包含。

unsigned char * read_file(FILE * file) //Don't forget to free retval after use
{
   int size = 0;
   unsigned int val;
   int startpos = ftell(file);
   while (fscanf(file, "%x ", &val) == 1)
   {
      ++size;
   }
   unsigned char * retval = (unsigned char *) malloc(size);
   fseek(file, startpos, SEEK_SET); //if the file was not on the beginning when we started
   int pos = 0;
   while (fscanf(file, "%x ", &val) == 1)
   {
      retval[pos++] = (unsigned char) val;
   }
   return retval;
}