-2

I wish to write a C program that reads in 1 byte hex values stored in a file. I have had a look around the Internet including StackOverflow but my requirement seems different from the average:

I have a text file with the following contents - which are single byte hex values:

35 36 37 38

In decimal that is:

53, 54, 55, 56

The hex values are the following ASCII characters

5 6 7 8

I want to read that in from a text file the which contains the ASCII 35 36 37 38 as four hex bytes. I have been tinkering with FILE pointers and fread() but it reads in the 35 value for example as 3 and 5 which is stored in a buffer as 33 35 (the hex for 3 and 5 separately). So my question is...

Short version:

Is there a way to read a file two ASCII characters at a time (not two bytes at a time because that would give different results!). Perhaps should I read into a char? Rather than presenting some code and stating it doesn't work as usually happens on SO, I'm not sure how to start with this so I have no code to present. You don't have to write the code for me but some guidance on how to approach the problem scenario would be good.

jwbensley
  • 10,534
  • 19
  • 75
  • 93
  • What about the spaces? – Kerrek SB Sep 04 '14 at 21:14
  • 2
    A person of your stature should know the score - you need to write some code and let us comment/fix it. – Ed Heal Sep 04 '14 at 21:16
  • @EdHeal - Why should one have to post code? Is it forbidden on StackOverflow to talk about how to approach a programming problem? Can we not discuss the logic of the problem, pseudo code even? – jwbensley Sep 04 '14 at 21:17
  • 2
    `fscanf(fp, "%x", &h)` ... `printf("%c ", (char)h);` – BLUEPIXY Sep 04 '14 at 21:20
  • @KerrekSB - Good point about the spaces, I'd like to ignore them, I'll update the post. Regarding the "is there a way" - again I should have been clearer on that too, I meant `is there a way that doesn't involve some really obscure or non-constructive code like casting to an int which is cast to base 16 and then cast to a popsicle and then printed from printf() into cout()` – jwbensley Sep 04 '14 at 21:21
  • Its fair to say my question is a duplicate of the post linked by the moderators but have you read all the answers - some of those are not good answers. – jwbensley Sep 04 '14 at 21:25

1 Answers1

2

It is indeed possible to read two characters at a a time:

unsigned int dehex(FILE * p)
{
    char two[2];
    if (2 != fread(two, 1, 2, p)) { abort(); }

    return as_hex(two[0]) * 16 + as_hex(two[1]);
}

unsigned int as_hex(char c)
{
    if ('0' <= c && c <= '9') { return c - '0'; }
    if ('a' <= c && c <= 'f') { return c + 10 - 'a'; }
    if ('A' <= c && c <= 'F') { return c + 10 - 'A'; }
    abort();
}
Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084