I am running the following C++ code on Coliru:
#include <iostream> #include <string> int main() { int num1 = 208; unsigned char uc_num1 = (unsigned char) num1; std::cout << "test1: " << uc_num1 << "\n"; int num2 = 255; unsigned char uc_num2 = (unsigned char) num2; std::cout << "test2: " << uc_num2 << "\n"; } I am getting the output:
test1: � test2: � This is a simplified example of my code.
Why does this not print out:
test1: 208 test2: 255 Am I misusing std::cout, or am I not doing the casting correctly?
More background
I want to convert from int to unsigned char (rather than unsigned char*). I know that all my integers will be between 0 and 255 because I am using them in the RGBA color model.
I want to use LodePNG to encode images. The library in example_encode.cpp uses unsigned chars in std::vector<unsigned char>& image:
//Example 1 //Encode from raw pixels to disk with a single function call //The image argument has width * height RGBA pixels or width * height * 4 bytes void encodeOneStep(const char* filename, std::vector<unsigned char>& image, unsigned width, unsigned height) { //Encode the image unsigned error = lodepng::encode(filename, image, width, height); //if there's an error, display it if(error) std::cout << "encoder error " << error << ": "<< lodepng_error_text(error) << std::endl; }
std::cin::operator<<(unsigned char)prints the character representation, just dostd::cout << num1if you want the integer.encodeOneStepfunction in the LodePNG library.cout. It does not tell me whether my cast frominttounsigned charis the right way to approach this problem. Would you confirm that it is the right way?