If I run this code:
std::cout << static_cast<uint8_t>(65);
It will output:
A
Which is the ASCII equivalent of the number 65.
This is because uint8_t is simply defined as:
typedef unsigned char uint8_t;
Is this behavior a standard?
Should not be a better way to define
uint8_tthat guaranteed to be dealt with as a number not a character?
I can not understand the logic that if I want to print the value of a uint8_t variable, it will be printed as a character.
P.S. I am using MSVS 2013.
The behavior is standard in that if
uint8_tis a typedef ofunsigned charthen it will always print a character asstd::ostreamhas an overload forunsigned charand prints out the contents of the variable as a character.In order to do this the C++ committee would have had to introduce a new fundamental type. Currently the only types that has a
sizeof()that is equal to 1 ischar,signed char, andunsigned char. It is possible they could use aboolbutbooldoes not have to have a size of 1 and then you are still in the same boat sincewill print
1, not42as any non zero is true and true is printed as1but default.I'm not saying it can't be done but it is a lot of work for something that can be handled with a cast or a function
C++17 introduces
std::bytewhich is defined asenum class byte : unsigned char {};. So it will be one byte wide but it is not a character type. Unfortunately, since it is anenum classit comes with it's own limitations. The bit-wise operators have been defined for it but there is no built in stream operators for it so you would need to define your own to input and output it. That means you are still converting it but at least you wont conflict with the built in operators forunsigned char. That gives you something like