【发布时间】:2014-12-27 10:37:50
【问题描述】:
我在Coliru 上运行以下 C++ 代码:
#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 中的库在std::vector<unsigned char>& image 中使用unsigned chars:
//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 我将其打印出来以测试转换是否有效。我想将整数转换为无符号字符,因此我可以将无符号字符传递给 LodePNG 库中的
encodeOneStep函数。 -
@WhozCraig 感谢您提供的链接,该链接是关于在传递给
cout时字符在 ASCII 格式中的显示方式。它并没有告诉我我从int到unsigned char的演员阵容是否是解决这个问题的正确方法。你会确认这是正确的方法吗? -
这显然不是正确的方法,因为它没有告诉你你想知道什么,而是让你感到困惑。
标签: c++ casting unsigned-char