//解决方案:使用按位运算符并完全删除 sstreams。 atoi 不正确地接受十六进制。//
namespace color_tools{
std::stringstream sstream;
}
int RGB_256_to_hex(signed short r, signed short g, signed short b){
std::string hex_col;
color_tools::sstream << std::hex << r << g << b;
hex_col = color_tools::sstream.str();
color_tools::sstream.str("");
color_tools::sstream.clear();
return atoi(hex_col.c_str());
}
例如,如果我传递 (0,0,255),则函数返回 0。这是不正确的,因为蓝色是 0000ff。如果我将函数的返回类型更改为字符串并只返回 hex_col,我会得到正确的结果。我假设问题一定出在 atoi() 上?
有点跑题:我可以用 __int8 类型替换带符号的短组件吗,因为它完全适合 256 色阶?
其他建议也将不胜感激。
最佳答案
是的,atoi 是问题所在。它假定您传递了一个十进制作为其参数,同时传递了一个十六进制。它读取数字直到第一个非数字(在你的例子中是四个零)并返回结果。
我认为您最好避免通过流进行这种复杂的转换,而使用简单的按位运算(例如移位和 OR),这将显着提高代码的可读性、性能和简洁性。
关于c++ - 为什么我的 RGB 转十六进制函数在传递颜色分量时返回 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19801604/