C ++将整数转换为十六进制字符串,用于Graphicsmagick中的Color

时间:2011-05-21 14:45:52

标签: c++ colors hex graphicsmagick

如何将0到255之间的整数转换为具有两个字符的字符串,包含数字的十六进制表示形式?

实施例

输入:180 输出:“B4”

我的目标是在Graphicsmagick中设置灰度颜色。所以,以同样的例子,我想要以下最终输出:

“#B4B4B4”

这样我就可以用它来分配颜色:颜色(“#B4B4B4”);

应该很容易,对吧?

3 个答案:

答案 0 :(得分:2)

你不需要。这是一种更简单的方法:

ColorRGB(red/255., green/255., blue/255.)

答案 1 :(得分:1)

您可以使用C ++标准库的IOStreams部分的本机格式化功能,如下所示:

#include <string>
#include <sstream>
#include <iostream>
#include <ios>
#include <iomanip>

std::string getHexCode(unsigned char c) {

   // Not necessarily the most efficient approach,
   // creating a new stringstream each time.
   // It'll do, though.
   std::stringstream ss;

   // Set stream modes
   ss << std::uppercase << std::setw(2) << std::setfill('0') << std::hex;

   // Stream in the character's ASCII code
   // (using `+` for promotion to `int`)
   ss << +c;

   // Return resultant string content
   return ss.str();
}

int main() {
   // Output: "B4, 04"
   std::cout << getHexCode(180) << ", " << getHexCode(4); 
}

Live example.

答案 2 :(得分:0)

使用printf格式说明符%x。或者,strtol将基数指定为16。

#include<cstdio>

int main()
{

    int a = 180;
    printf("%x\n", a);

    return 0;
}