2014-10-31 56 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