3

I am trying to read a small integer value (less than 10) to a uint8_t variable. I do it like this

uint8_t myID = atoi(argv[5]);

However when I do this

std::cout << "My ID is "<< myID <<std::endl;

It prints some non-alphanumeric character. There is no issue when myID is of type int. I tried casting explicitly by doing

uint8_t myID = (uint8_t)atoi(argv[5]);  

But the results are the same. Could anyone explain why this is the case and if there is any possible solution?

2 Answers2

4

uint8_t is not a separate data type. On systems that provide it the actual type is aliased to some standard data type, most commonly, an unsigned char.

Operator << provides an overload that takes unsigned char, and prints it as a character. When you are printing your uint8_t variable as an int, cast it to an int for printing:

std::cout << "My ID is "<< int(myID) <<std::endl;
//                         ^^^^^

Demo.

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

That's because on your platform, uint8_t is a typedef for an unsigned char.

And the ostream overloaded << for an unsigned char outputs a character, rather than a number, since the clever C++ folk thought that to be sensible. It normally is.

You can fix this by casting to an int, which will always be able to accept an uint8_t value.

(Note that prior to C++14, a char could be a 1's complement or signed magnitude 8 bit signed type, so it could be different to uint8_t).

Xavier Imbs
  • 212
  • 2
  • 10