c++,stl.将具有rgb颜色的字符串转换为3个int值

c++, stl. Convert string with rgb color to 3 int values?

本文关键字:转换 字符串 3个 int 颜色 stl rgb c++      更新时间:2023-10-16

字符串看起来像"#12346",结果应该是:

int r = 0x12;
int g = 0x34;
int b = 0x56;

或者简单地说是c++中该任务的相反:

如何将RGB int值转换为字符串颜色

我知道我可以将当前字符串拆分为3个子字符串,但如何将它们实现为十六进制值?

使用标准库的std::hex:

#include <iostream>
#include <sstream>
int main()
{
   // The hex code that should be converted ...
   std::string hexCode;
   std::cout << "Please enter the hex code: ";
   std::cin >> hexCode;
   // ... and the target rgb integer values.
   int r, g, b;
   // Remove the hashtag ...
   if(hexCode.at(0) == '#') {
      hexCode = hexCode.erase(0, 1);
   }
   // ... and extract the rgb values.
   std::istringstream(hexCode.substr(0,2)) >> std::hex >> r;
   std::istringstream(hexCode.substr(2,2)) >> std::hex >> g;
   std::istringstream(hexCode.substr(4,2)) >> std::hex >> b;
   // Finally dump the result.
   std::cout << std::dec << "Parsing #" << hexCode 
      << " as hex gives (" << r << ", " << g << ", " << b << ")" << 'n';
}

您应该首先获取数字,去掉#。

然后,您可以使用字符串流:

#include <sstream>
...
{
  using namespace std;
  stringstream ss("123456");
  int num;
  ss >> hex >> num;
}

最后通过划分得到每个组件:

// Edit: I did it from memory and got it wrong, its % 0x100, not % 0xff.
int r = num / 0x10000;
int g = (num / 0x100) % 0x100;
int b = num % 0x100;

编辑:不知道std::stoi(可用于C++11)。谢谢@juancopanza。有了它,你可以更改代码的第一部分:

#include <string>
...
{
  using namespace std;
  int num = stoi("123456", 0, 16);
  int r = ....
}

您可以生成三个子字符串,将它们转换为int,然后使用std::hex?

看看这个。

一旦字符串中的每个部分都有了,就可以使用strtol()将其转换为数字。请确保使用16作为"基本"参数,因为您的值是十六进制的。

将字符串拆分为3个单独的数字后,请尝试sscan()。

这里有一个简单的解决方案:

unsigned int str_to_hex(char const * p, char const * e) noexcept
{
    unsigned int result = 0;
    while (p != e)
    {
        result *= 16;
        if ('0' <= *p && *p <= '9') { result += *p - '0';  continue; }
        if ('A' <= *p && *p <= 'F') { result += *p + 10 - 'A'; continue; }
        if ('a' <= *p && *p <= 'f') { result += *p + 10 - 'a'; continue; }
        return -1;
    }
}
std::tuple<unsigned char, unsigned char, unsigned char>
str_to_col(std::string const & s)
{
    if (str.length() != 7 || s[0] == '#') { /* error */ }
    auto r = str_to_hex(str.data() + 1, str.data() + 3);
    auto g = str_to_hex(str.data() + 3, str.data() + 5);
    auto b = str_to_hex(str.data() + 5, str.data() + 7);
    if (r == -1 || g == -1 || b == -1) { /* error */ }
    return {r, g, b};
}

如果您在其他地方验证了您的输入,您可以将最后一个函数缩写为仅return { str_to_hex(...), ... };


或者,您根本不需要拆分字符串:

std::string s = "#123456";
auto n = str_to_hex(s.data() + 1, s.data() + 7);
auto r = n / 0x10000, g = (n / 0x100) % 0x100, b = n % 0x10000;

除了自制的str_to_hex函数,您还可以使用标准库的转换函数,如std::strtoul(s.substring(1), nullptr, 16)

反之亦然:uint8_t三元组到字符串

#include <string>
#include <iostream>
#include <sstream>
std::string to_hex_string(uint8_t red, uint8_t green, uint8_t blue) {
    // r, g, b -> "#RRGGBB"
    std::ostringstream oss;
    oss << '#';
    oss.fill('0');
    oss.width(6);
    oss << std::uppercase << std::hex << ((red << 16) | (green << 8) | blue);
    return oss.str();
}