Search code examples
c++type-conversionunsignedunsigned-char

Garbage values when array declared as unsigned char


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.