Is this behavior a standard
The behavior is standard in that if uint8_t
is a typedef of unsigned char
then it will always print a character as std::ostream
has an overload for unsigned char
and prints out the contents of the variable as a character.
Should not be a better way to define uint8_t
that guaranteed to be dealt with as a number not 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 is char
, signed char
, and unsigned char
. It is possible they could use a bool
but bool
does not have to have a size of 1 and then you are still in the same boat since
int main()
{
bool foo = 42;
std::cout << foo << '\n';
}
will print 1
, not 42
as any non zero is true and true is printed as 1
but 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::byte
which is defined as enum class byte : unsigned char {};
. So it will be one byte wide but it is not a character type. Unfortunately, since it is an enum class
it 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 for unsigned char
. That gives you something like
std::ostream& operator <<(std::ostream& os, std::byte b)
{
return os << std::to_integer<unsigned int>(b);
}
std::istream& operator <<(std::istream& is, std::byte& b)
{
unsigned int temp;
is >> temp;
b = std::byte{b};
return is;
}
int main()
{
std::byte foo{10};
std::cout << foo;
}
uint8_t
as a small unsigned integer you need to cast it before outputting it. Like e.g.static_cast<uint32_t>(some_uint8_t_variable)
– Rajewskichar
is guaranteed to have asizeof()
of 1. – Wearychar
. Yes, C++ could have added a new type, but that would conflict with C, which is where these typedefs originated. – Henchmanstd::cout << +static_cast<uint8_t>(65);
will do what you want. – Henchmanbool
and everything else has an implementation defined size. The only type the exist with a know size of 1 is the char variants. – Weary+
is a unary operator that acts a lot like the unary-
, except that it doesn't negate the value. It's generally viewed as pointless, but it is useful here, because, as an arithmetic operator, the compiler promotes its argument toint
. So+x
is equivalent to(int)x
. – Henchman+static_cast<uint8_t>(65)
failed on your compiler – Lutistuint[_fast|_least]N_t
types this way. You have to first cast tounsigned long long
, for instance. – Irenics