C read X bytes from a file, padding if needed

Posted by Hunter McMillen on Stack Overflow See other posts from Stack Overflow or by Hunter McMillen
Published on 2012-03-18T17:41:47Z Indexed on 2012/03/18 17:55 UTC
Read the original article Hit count: 137

Filed under:

I am trying to read in an input file 64 bits at a time, then do some calculations on those 64 bits, the problem is I need to convert the ascii text to hexadecimal characters. I have searched around but none of the answers posted seem to work for my situation.

Here is what I have:

int main(int argc, int * argv)
{
   char buffer[9];
   FILE *f;
   unsigned long long test;

   if(f = fopen("input2.txt", "r"))
   {
     while( fread(buffer, 8, 1, f) != 0) //while not EOF read 8 bytes at a time
     {
       buffer[8] = '\0';
       test = strtoull(buffer, NULL, 16); //interpret as hex
       printf("%llu\n", test);
       printf("%s\n", buffer);
     }
     fclose(f);
   }
}

For an input like this:

"testing string to hex conversion"

I get results like this:

0 
testing  
0 
string t 
0 
o hex co 
0 nversion

Where I would expect:

74 65 73 74 69 6e 67 20 <- "testing" in hex
testing

73 74 72 69 6e 67 20 74 <- "string t" in hex
string t

6f 20 68 65 78 20 63 6f <- "o hex co" in hex
o hex co

6e 76 65 72 73 69 6f 6e <- "nversion" in hex
nversion

Can anyone see where I misstepped?

© Stack Overflow or respective owner

Related posts about c