0

I've looked everywhere trying to figure out what I'm doing wrong and can't seem to figure out WHY this block of code isn't handling hexadecimal numbers correctly.

FILE *listFile = fopen(argv[1], "r");

unsigned int hexIndex;

if(listFile == NULL){
    printf("error\n");
    return 0;
}

while(!feof(listFile))
{
    fscanf(listFile, "%x\n", &hexIndex);

    printf("hexindex %d\n", hexIndex);
    if(hashInsert(hexIndex) == 0)
    {
        printf("uniques: %d\n", uniques);
        uniques++;
    }
}

For example, given a file with the following 3 hexadecimal addresses:

0xFFFFFFFFFF

0x7f1a91026b00

0x7f1a91026b03

The program prints out:

hexindex -1

hexindex -1862112512

hexindex -1862112509

which I'm 100% sure is incorrect. I've spent hours trying to figure out what I've done wrong, and I feel that I might be overlooking something simple. I've tried using different integer types like size_t, longs, etc. but run into the same exact output every time.

Can anybody give me some insight as to what I might be doing wrong?

Mikey Chen
  • 2,370
  • 1
  • 19
  • 31

1 Answers1

1

You should use %u or %x to printf an unsigned int. Currently you are using %d which causes undefined behaviour.

A second thing to check is that the intended values will fit into unsigned int. Some of your sample values are 48 bits long. If your system has 32-bit unsigned int then you cannot use unsigned int for this purpose.

The portable way to go here is to use uint64_t as the variable type, and the scanf hex specifier is SCNx64 and the printf specifier is PRIu64 or PRIx64. For example:

#include <inttypes.h>
uint64_t hexIndex;

// ...

while( 1 == fscanf(listFile, "%" SCNx64, &hexIndex) )
{
    printf("hexindex %" PRIu64 "\n", hexIndex);

    if(hashInsert(hexIndex) == 0)
    {
        printf("uniques: %d\n", uniques);
        uniques++;
    }
}

(note: don't use while...feof)

Community
  • 1
  • 1
M.M
  • 138,810
  • 21
  • 208
  • 365
  • I already tried using uint64_t - but this doesn't fix the fundamental problem that hexIndex is always being assigned a negative value. Using "%u" in printf will print a positive number, but when I use the actual hexIndex number, it's still negative (which is causing me a lot of problems because hashInsert() tries to access a negative index of an array. I tried to use SCNx64 and uint64_t instead, and I'm still getting that same error. The hex values I'm getting simply don't match up to what I think they are. – Mikey Chen Feb 27 '15 at 05:17
  • @hendersawn `unsigned int` and `uint64_t` cannot hold negative values. You must be misinterpreting whatever symptoms cause you to think that they can. – M.M Feb 27 '15 at 05:25