Hunter McMillen
Hunter McMillen

Reputation: 61512

Read 64bit Hex value from a file in C

I have a text file that looks like this:

0000000000000000    0000000000000000
FFFFFFFFFFFFFFFF    FFFFFFFFFFFFFFFF
3000000000000000    1000000000000001
1111111111111111    1111111111111111
0123456789ABCDEF    1111111111111111
1111111111111111    0123456789ABCDEF
0808080808080808    0000000000000000
FEDCBA9876543210    0123456789ABCDEF
7CA110454A1A6E57    01A1D6D039776742
0131D9619DC1376E    5CD54CA83DEF57DA

What would be the best way to read these in using C? My first attempt tried to use fscanf() to read them into int variables, but these are 64-bit hex values, so the int type is too small to read them in completely and part of the values were truncated.

My attempt:

while( fscanf(infile, "%x %x", &key, &plaintext) != EOF )
{
    printf("%x\t\t%x\n", key, plaintext);

}

Is there a type large enough to hold this in C? If not what are my other options for storage? Char arrays?

Thanks

Please note that I am using ANSI C, with GCC 4.5.2 (MinGW)

Upvotes: 0

Views: 3340

Answers (2)

asaelr
asaelr

Reputation: 5456

Just use the macro and typedef from inttypes.h:

uint64_t key,plaintext;
fscanf(infile,"%u" PRIx64 " %u" PRIx64,&key, &plaintext);

Upvotes: 4

Kerrek SB
Kerrek SB

Reputation: 477010

In C99, C11 and C++11, you can use strtoull, e.g. strtoull(s, NULL, 16);, from the header <stdlib.h>.

Upvotes: 2

Related Questions