1

I want to print a variable as hex:

#include <iostream>
#include <string>
#include <cstdint>

int main() {
    auto c = 0xb7;

    std::cout << std::hex << static_cast<unsigned char>(c) << std::endl;
    std::cout << std::hex << static_cast<unsigned>(static_cast<unsigned char>(c)) << std::endl;

    std::cout << std::hex << (uint8_t)(c) << std::endl;
    std::cout << std::hex << (unsigned)(uint8_t)(c) << std::endl;

    return 0;
}

The output seems to be:

\ufffd (tries to print it as a char)
b7
\ufffd (tries to print it as a char)
b7

I do understand that c has higher bits set (10110111), but I cast it to uint8_t and unsigned char once already.

Why do I have to cast uint8_t or unsigned char to unsigned again to get the expected output?

PoorLuzer
  • 24,466
  • 7
  • 31
  • 35

1 Answers1

1

std::hex sets the basefield of the stream str to hex as if by calling str.setf(std::ios_base::hex, std::ios_base::basefield).

When this basefield hex bit is set, iostreams use hexadecimal base for integer I/O.

Code

#include <iostream>

int main()
{
    int i = 0xb7;
    unsigned u = 0xb7;
    char c = static_cast<char>(0xb7);
    unsigned char b = 0xb7;

    std::cout << std::hex << i << std::endl;
    std::cout << std::hex << u << std::endl;
    std::cout << std::hex << c << std::endl;
    std::cout << std::hex << b << std::endl;
    return 0;
}

Output

b7
b7
�
�

I suspect this output to vary on a Windows (non UTF-8) system.

YSC
  • 38,212
  • 9
  • 96
  • 149
  • So does this mean that unless the type is an `int`, `iostreams` will ignore the `std::hex` modifier and print everything as a raw byte anyways? Even an `uint8_t` which I assumed to be a byte (incorrect assumption?) – PoorLuzer Dec 11 '15 at 23:48
  • Doesn't have to be `int` in particular, does have to be an integral type that is not a character type. Standard doesn't say if `uint8_t` is a character type - it is allowed to be but not required. On your system it is. See linked question. – Ben Voigt Dec 12 '15 at 00:24
  • Great answer. Loved the references. I'll email you shortly at the contact info. Would you be able to review some of my unanswered questions? (two of them below) – PoorLuzer Dec 28 '15 at 22:29
  • http://stackoverflow.com/questions/873356/challenges-in-writing-wrappers-for-c-functions-so-that-they-can-be-used-from-c http://stackoverflow.com/questions/874161/c-tokenizer-and-it-returns-empty-too-when-fields-are-missing-yay – PoorLuzer Dec 28 '15 at 22:29