0

//SOLUTION: Use bitwise operators and drop sstreams completely. atoi does not properly accept hex.//

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());

}

If I pass, for example, (0,0,255) then the function returns 0. This is not correct as the color blue is 0000ff. If I change the return type of the function to a string and just return hex_col I get the proper result. I'm assuming the issue must be with atoi()?

A bit off topic: Can I replace the signed short components with the __int8 type since this perfectly fits 256 color steps?

Miscellaneous suggestions would also be appreciated.

4

1 回答 1

1

是的,atoi 是问题所在。它假定您传递了一个十进制作为其参数,而您传递了一个十六进制。它读取数字直到第一个非数字(在您的情况下为四个零)并返回结果。

我认为您最好避免通过流进行这种复杂的转换,并使用简单的按位运算,如移位和 OR,这将显着提高代码的可读性、性能和简单性。

于 2013-11-06T00:12:12.973 回答