我上Coliru运行以下C++代码:从`int`投射到`无符号char`
#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";
}
我正在输出:
test1: �
test2: �
这是一个简化的例子我码。
为什么这个没有打印出:
test1: 208
test2: 255
我是否滥用std::cout
,还是我没有做正确的铸造?
更多的背景
我想转换从int
到unsigned char
(而不是unsigned char*
)。我知道我所有的整数都在0到255之间,因为我在RGBA颜色模型中使用它们。
我想用LodePNG来编码图像。在example_encode.cpp
库使用unsigned char
S 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)'打印字符表示,只需要'std :: cout << num1'即可。 – user657267 2014-10-31 07:01:04
@ user657267我打印出来测试转换是否奏效。我想将整数转换为无符号字符,因此我可以将unsigned char传入LodePNG库中的'encodeOneStep'函数。 – user4063326 2014-10-31 07:03:01
[**阅读此**](http://stackoverflow.com/questions/11236759/displaying-chars-as-ints-without-explicit-cast)。 – WhozCraig 2014-10-31 07:03:48