1

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

例子

输入:180 输出:“B4”

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

“#B4B4B4”

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

应该很容易吧?

4

3 回答 3

2

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

ColorRGB(red/255., green/255., blue/255.)
于 2011-05-21T14:55:49.330 回答
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); 
}

活生生的例子。

于 2011-05-21T14:52:57.007 回答
0

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

#include<cstdio>

int main()
{

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

    return 0;
}
于 2011-05-21T14:49:29.183 回答