从文件中读取十六进制

时间:2014-10-01 22:15:28

标签: c file hex

我正在尝试从文本文件中读取十六进制值。然后我需要存储它们各自的4位二进制等价物,以便我可以访问各个位进行比较。 在文件中,十六进制采用以下格式:

5104
de61
567f

我希望每行能够以二进制形式存储每一行​​,以便我可以访问特定的位,也许是在数组中?喜欢: {0,1,1,0,0,0,0,1 ...}

我对理解C的模糊尝试已经产生了这个:

int main(int argc, char *argv[]){
    FILE *file;
    char instructions[8];
    file = fopen(argv[1], "r");
    while(fgets(instructions, sizeof(instructions), file) != NULL){
        unsigned char a[8];
        int i = 0;
        while (instructions[i] != '\n'){
            int b;
            sscanf(&instructions[i], "%2x", &b);
            a[i] = b;
            i += 2;
        }
    }
    fclose(file);
    return 0;
}

1 个答案:

答案 0 :(得分:2)

取自here。使用此代码,您可以按原样读取文件。

#include <stdio.h>

int main() {
    FILE *f;
    unsigned int num[80];
    int i=0;
    int rv;
    int num_values;

    f=fopen("test.txt","r");
    if (f==NULL){
        printf("file doesnt exist?!\n");
        return 1;
    }

    while (i < 80) {
        rv = fscanf(f, "%x", &num[i]);

        if (rv != 1)
            break;

        i++;
    }
    fclose(f);
    num_values = i;

    if (i >= 80)
    {
        printf("Warning: Stopped reading input due to input too long.\n");
    }
    else if (rv != EOF)
    {
        printf("Warning: Stopped reading input due to bad value.\n");
    }
    else
    {
        printf("Reached end of input.\n");
    }

    printf("Successfully read %d values:\n", num_values);
    for (i = 0; i < num_values; i++)
    {
        printf("\t%x\n", num[i]);
    }

    return 0;
}

现在,如果你想在二进制中转换十六进制,你可以用很多来做。检查一些提供方法的链接。

  1. Convert a long hex string in to int array with sscanf
  2. Source Code to Convert Hexadecimal to Binary and Vice Versa
  3. C program for hexadecimal to binary conversion
  4. 仅供参考,以下是第一个链接的代码:

    const size_t numdigits = strlen(input) / 2;
    
    uint8_t * const output = malloc(numdigits);
    
    for (size_t i = 0; i != numdigits; ++i)
    {
      output[i] = 16 * toInt(input[2*i]) + toInt(intput[2*i+1]);
    }
    
    unsigned int toInt(char c)
    {
      if (c >= '0' && c <= '9') return      c - '0';
      if (c >= 'A' && c <= 'F') return 10 + c - 'A';
      if (c >= 'a' && c <= 'f') return 10 + c - 'a';
      return -1;
    }