2014-10-31 54 views
1

我上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,还是我没有做正确的铸造?


更多的背景

我想转换从intunsigned 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; 
} 
+1

'std :: cin :: operator <<(unsigned char)'打印字符表示,只需要'std :: cout << num1'即可。 – user657267 2014-10-31 07:01:04

+0

@ user657267我打印出来测试转换是否奏效。我想将整数转换为无符号字符,因此我可以将unsigned char传入LodePNG库中的'encodeOneStep'函数。 – user4063326 2014-10-31 07:03:01

+1

[**阅读此**](http://stackoverflow.com/questions/11236759/displaying-chars-as-ints-without-explicit-cast)。 – WhozCraig 2014-10-31 07:03:48

回答

1

的std ::法院是正确=)

按ALT然后2 0 8 这是你与test1的打印字符。控制台可能不知道如何正确打印,因此输出问号。同样的事情与255.读取png并将其放入std :: vector后,没有用它写入屏幕的问题。该文件包含不可写入的二进制数据。

如果你想看到“208”和“255”,你不应该将它们转换为unsigned char第一,或指定要打印的数字,如int例如,像这样

std::cout << num1 << std::endl; 
std::cout << (int) uc_num1 << std::endl; 

你正在寻找一个std :: cout的特殊情况,这起初并不容易理解。

当调用std :: cout时,它检查右侧操作数的类型。在你的情况下,std::cout << uc_num1告诉cout操作数是一个无符号字符,所以它不执行转换,因为无符号字符通常是可打印的。试试这个:

unsigned char uc_num3 = 65; 
std::cout << uc_num3 << std::endl; 

如果你写std::cout << num1,那么cout会意识到你正在打印一个int。然后它会将int转换为一个字符串并为您打印该字符串。

你可能想检查一下C++操作符重载以了解它是如何工作的,但目前它并不是非常重要,你只需要认识到std :: cout对于你试图打印的不同数据类型可以有不同的行为。

+0

谢谢你的出色答案!它清除了我所有的困惑。 – user4063326 2014-10-31 07:25:16