Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is reading uint8_t as hex not working as expected?

Tags:

c++

iostream

Consider code like this:

#include <iostream>
#include <sstream>

int main()
{
    std::stringstream ss;
    ss << "a0 b1";

    uint8_t byte;
    ss >> std::hex >> byte;    

    std::cout << std::hex << byte << std::endl;

    return 0;
}

Why does this output a instead of a0 even though a0 fits in uint8_t as hex?

like image 864
juzzlin Avatar asked Jun 04 '19 14:06

juzzlin


1 Answers

Because uint8_t is also (probably) unsigned char, for which special rules exist when you perform formatted extraction from a C++ stream.

Unfortunately this is just an alias, not a distinct type.

Basically it's skipping the "lexically convert to a number" step because it thinks you want to pull out a character. The character 'a'.

I think you'll want to read into an unsigned int then downsize if needed.

If you do downsize to a uint8_t, you're also going then to have to promote it back to a larger int (lol) for much the same reason, to trigger serialisation.

(live demo)

To be honest I'd just avoid the small fixed-width types when dealing with streams (unless you're doing unformatted work with read() and write()). It's too easy to forget about this problem.

like image 137
Lightness Races in Orbit Avatar answered Dec 06 '22 18:12

Lightness Races in Orbit