Garbage values when array declared as unsigned char
-
30-04-2021 - |
Question
When an array is declared as unsigned char and initialized with values in the range 0x00-0xff and printed using cout, I get garbage values as follows
+ ( �
~ � � �
� O
� � <
May I know how to use use single byte for the numbers and yet be able to use cout ?
Solution
Because it's an unsigned char
, std::cout
is passing them to the terminal and it's being displayed as a character set (Well, attempting, anyway - the values are outside the range of valid printable characters for the character set you're using).
Cast to unsigned int
when outputting with cout
.
OTHER TIPS
Char types are displayed as characters by default. If you want them displayed as integers, you will have to convert them first:
unsigned char value = 42;
std::cout << static_cast<unsigned int>(value);
Those aren't garbage values. Those are what the character represents. To print it as an int, simply cast to unsigned int
at output time:
cout << (unsigned int) some_char;