0

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 ?

2
  • can we see both the initialization code and the printing code? Commented Feb 18, 2012 at 6:29
  • You're trying to print non-printable characters. Commented Feb 18, 2012 at 6:33

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

1

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.