1

I am trying to read hex values from a text file. I then need to store their individual 4 bit binary equivalents so that i can access the individual bits for comparison. In the file the hex is in this format:

5104
de61
567f

And I would like to be able to have each line stored one at a time as binary in such a way that I can access a specific bit, maybe in an array? Like: {0,1,1,0,0,0,0,1...}

My vague attempts at understanding C has yielded this:

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;
}
Stoked
  • 13
  • 1
  • 4

1 Answers1

2

Taken from here. With this code you can read the file as it is.

#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;
}

Now, if you want to convert hex in binary, you could do it with many was. Check some links that provide methods.

  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

Just for the reference, here is the code from the first link:

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;
}
Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305