Behavior of cout << hex with uint8 and uint16

后端 未结 3 1561
刺人心
刺人心 2021-02-15 00:19

I\'m noticing that cout << hex is giving me strange results, and I cannot find anywhere that answers why. What I am doing is simply assigning some values to

相关标签:
3条回答
  • 2021-02-15 00:29

    The other answers are correct about the reason. The simplest fix is:

    cout << hex << +a << endl;
    

    Demonstration: http://ideone.com/ZHHAHX

    It works because operands undergo integer promotion.

    0 讨论(0)
  • 2021-02-15 00:34

    uint8_t is an alias for unsigned char. You're essentially printing a character with the value 0xab, which might be an invalid character depending on your encoding.

    This would be solvable by casting it to another integer type, converting its value to a string in advance or writing some sort of a wrapper class that implements std::ostream& operator<<(std::ostream&, const ClassName&).

    0 讨论(0)
  • 2021-02-15 00:44

    std::uint8_t is an alias for unsigned char:

    typedef unsigned char uint8_t;
    

    So the overload of the inserter that takes a char& is chosen, and the ASCII representation of 0xab is written, which could technically vary by your operating system, as 0xab is in the range of Extended ASCII.

    You have to cast it to an integer:

    std::cout << std::hex << static_cast<int>(a) << std::endl;
    
    0 讨论(0)
提交回复
热议问题