首页 文章

C将RGB转换为十六进制

提问于
浏览
-2

我在十六进制代码中需要关于rgb covertor的帮助 . 我正在尝试使函数返回十六进制代码 . 我需要cString为十六进制 . 对于导入我使用:

dwTitleColor1 // Red
    dwTitleColor2 // Green
    dwTitleColor3 // Blue

const char * CHARACTER::GetTitleColor() const
{
    static char cString[CHARACTER_NAME_MAX_LEN  + 1];
    dwTitleColor1 = 0
    dwTitleColor2 = 0
    dwTitleColor3 = 0

    snprintf(cString, sizeof(cString), "r:%d, g:%d, b:%d.",  dwTitleColor1, dwTitleColor2, dwTitleColor3);
    return cString;
}

2 回答

  • 1

    你为什么不用C工具?

    std::string CHARACTER::GetTitleColor() const
    {
        std::ostringstream buffer;
        buffer.flags(std::ios_base::hex | std::ios_base::left);
        buffer.fill('0');
        buffer <<"r: " <<std::setw(2) <<dwTitleColor1
               <<", g: " <<std::setw(2) <<dwTitleColor2
               <<", b: " <<std::setw(2) <<dwTitleColor3;
        return buffer.str();
    }
    

    这会将每种颜色写为2位十六进制数 . 随意调整格式:如果需要小数,则删除标记,如果不需要前导0,则删除 setw 并填充 .

    (并重命名该类,除了C程序中的宏之外,您不希望使用全部大写) .

    [edit] 由于它似乎引起了一些混乱,我想声明我故意将返回类型更改为 std::string . 因为C字符串是 std::string ,而不是 char* . 它的用途很简单:

    // Assuming myChar is a CHARACTER instance
    std::string colorA = myChar.GetTitleColor();    // straightforward
    auto colorB = myChar.GetTitleColor();           // better, color gets automatic type from method return type
    const auto & colorC = myChar.GetTitleColor();   // if we won't modify it, even better.
    

    您可以随意使用返回的字符串 . 你不必释放它 . 它一直有效,直到它超出范围(与静态char *相反,如果你在另一个字符上调用 GetTitleColor ,它会被覆盖) .

    如果你真的别无选择,你可以随时做与静态相同的事情:用这两个代替返回行:

    static std::string result = buffer.str();
    return result.c_str();
    

    它具有与静态版本完全相同的警告:再次调用 GetTitleColor() 将使先前返回的指针无效 .

  • 0

    这应该这样做:

    snprintf(cString, sizeof(cString), "r:%x, g:%x, b:%x.",  
        dwTitleColor1, dwTitleColor2, dwTitleColor3);
    

相关问题