2014-10-01 161 views
1

我想从文本文件中读取十六进制值。然后我需要存储它们各自的4位二进制等值,这样我可以访问各个位进行比较。 在文件中的十六进制的格式如下:从文件中读取十六进制

5104 
de61 
567f 

而且我希望能够有一次存储一个二进制以这样的方式每行,我可以访问特定位,也许在数组?像: {0,1,1,0,0,0,0,1 ...}

我在理解ç模糊的尝试已经取得了这一点:

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; 
} 
+2

**发表你试过什么**,和你为什么认为它会起作用以及为什么它似乎失败的猜测。 – WhozCraig 2014-10-01 22:16:54

+0

将它们存储在字节中,并使用按位运算符来检查位 – 2014-10-01 22:17:20

+0

“我试过了我能想到的所有方法”这很好。请展示您最接近的尝试,因为入门级问题的良好尝试通常足以修复。 – dasblinkenlight 2014-10-01 22:18:16

回答

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

只是为了参考,这里是从第一个链接代码:

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; 
} 
相关问题