I’d like to take the next two hex characters from a stream and store them as the associated associated hex->decimal numeric value in a char.
So if an input file contains 2a3123, I’d like to grab 2a, and store the numeric value (decimal 42) in a char.
I’ve tried
char c;
instream >> std::setw(2) >> std::hex >> c;
but this gives me garbage (if I replace c with an int, I get the maximum value for signed int).
Any help would be greatly appreciated! Thanks!
edit: I should note that the characters are guaranteed to be within the proper range for chars and that the file is valid hexadecimal.
OK I think dealing with ASCII decoding is a bad idea at all and does not really answer the question.
I think your code does not work because
setw()oristream::width()works only when you read tostd::stringorchar*. I guess it from hereHow ever you can use the goodness of standard c++ iostream converters. I came up with idea that uses
stringstreamclass andstringas buffer. The thing is to readnchars into buffer and then usestringstreamas a converter facility.I am not sure if this is the most optimal version. Probably not.
Code:
Result:
And as you can see not very error resistant. Nonetheless, works for the given conditions, can be expanded into a loop and most importantly uses the
iostreamconverting facilities so no ASCII magic from your side. C/ASCII would probably be way faster though.PS. Improved version. Uses simple
char[2]buffer and uses non-formatted write/read to move data thorough the buffer (get/writeas opposed tooperator<</operator>>). The rationale is pretty simple. We do not need any fanciness to move 2 bytes of data. We ,however, use formatted extractor to make the conversion. I made it a loop version for the convenience. It was not super simple though. It took me good 40 minutes of fooling around to figure out very important lines. With out them the extraction works for 1st 2 characters.Sample output:
Please note, the
cwas not read as intended.I found everything needed here http://www.cplusplus.com/reference/iostream/