Question

I have a file with hexadecimals binary values and what I want is to read those values 2 by 2 byte by byte and store them into an array. I mean:

I have a file(This is not an ascii string, I need an HEX editor to open this file)

00B011070000FF

and what I want is:

 ITA[0] = 00;
 ITA[1] = B0;
 ITA[2] = 11;
 ITA[3] = 07;
 ITA[4] = 00;
 ITA[5] = 00;
 ITA[6] = FF;

ITA is an unsigned int

How can I do this?

Thanks in advance.

Solution:

    FILE *pFile = fopen("/ita/hex", "r");

    if (!pFile) {
            printf("Error abriendo archivo\n");
        }

    fseek(pFile, 0, SEEK_END);
    int size = ftell(pFile);
    fseek(pFile, 0, SEEK_SET);
    printf("%i\n",size);
    unsigned int ITA[size];
    for (i = 0; i < size; i++) {
        char value;
        fread(&value, 1, 1, pFile);
        ITA[i] = (unsigned int) value;
    }
    fclose(pFile);
    printf(" ITA is : %X", crcFast2(ITA, size));// crcFAST2 calculates the crc of the hexadecimals

Thank you again!!

Was it helpful?

Solution

Since the file contains binary data and ITA is an unsigned int array:

#include <stdio.h>

void readBinary(char *const filename, unsigned int *const ITA, const int size) {
    FILE *pFile = fopen(filename, "r");
    for (int i = 0; i < size; i++) {
        char value;
        fread(&value, 1, 1, pFile);
        ITA[i] = (unsigned int) value;
    }
    fclose(pFile);
}

Parameter size should be 7 in the scenario you described.

OTHER TIPS

If it is binary then you can just mmap() the file straight into memory

See this page for where I have shamelessly stolen the following code

#include <unistd.h>
#include <sys/types.h>
#include <sys/mman.h>

int fd, pagesize;
unsigned char *data; /* NB note char array not unsigned int as requested */

fd = open("foo", O_RDONLY);
pagesize = getpagesize();
data = mmap((caddr_t)0, pagesize, PROT_READ, MAP_SHARED, fd, pagesize);

Note that the octet data will be packed into a char array, which is a preferable way to store octet data but is not what was requested

Also this: http://www.gnu.org/software/libc/manual/html_node/Memory_002dmapped-I_002fO.html

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top