我上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