• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

Help! Reading in hex values from file to unsigned char in C.

JonTheBaller

Golden Member
I have a file called "input.txt". Within input is a string of hexadecimal values:

a7b38fd9cb24a38de31729... (etc)

I want to read in the values as bytes, rather than ASCII characters. So for the example above, I would want to read in the form:

{ 0xa7, 0xb3, 0x8f, 0xd9, 0xcb, ... }

This seems like a pretty simple thing to do, but I'm stuck. Please help!

Thanks!
 
Originally posted by: EmperorRob
What functions are you using to open/close/read from this file?

Rob, I figured out my problem. I simply read in the characters as ASCII, and if it was in the range 0-9 I subtracted 48 (48 == '0'); if it was in the range a-f I subtracted 87 (97 == 'a'). That gets me two half bytes (nybble?). Then I bit shift the first half-byte 4 bits, and or it with the second half-byte.

I thought there might be a more "seamless" method of doing this.
 
Originally posted by: johnnytightlips
Originally posted by: BingBongWongFooey
Use c++ and boost::lexical_cast 😉

I googled and within 10 seconds (this is why STFW is in my sig 😉) found this

Well I'm using C, not C++.

That's what the winky face is for.

Seriously, I found that solution in a few seconds of googling; I'm sure you can find a nice solution with a little more searching.
 
Originally posted by: johnnytightlips


Rob, I figured out my problem. I simply read in the characters as ASCII, and if it was in the range 0-9 I subtracted 48 (48 == '0'); if it was in the range a-f I subtracted 87 (97 == 'a'). That gets me two half bytes (nybble?). Then I bit shift the first half-byte 4 bits, and or it with the second half-byte.

I thought there might be a more "seamless" method of doing this.

I would read the file as text. I just got through figuring out how to do this in perl so I got curious. What I wound up having to do is read the hex values in as strings and prepend an 'x' to them then sprintf with %x.
 
Back
Top