从十六进制字符串颜色到RGB颜色

From hexadecimal string color to an RGB color

本文关键字:颜色 RGB 字符串 十六进制      更新时间:2023-10-16

如何将hexadecimal字符串颜色#FF0022值转换为C++RGB

:

#FF0022

r:255
g:0
b:34

我不知道怎么做,我搜索了谷歌没有运气,请告诉我如何,这样我可以了解更多关于它

解析字符串,然后使用strtol()将每组两个字符转换为小数

代码示例:

#include <iostream>
#include <string>
#include <vector>
using namespace std;
std::vector<std::string> SplitWithCharacters(const std::string& str, int splitLength) {
  int NumSubstrings = str.length() / splitLength;
  std::vector<std::string> ret;
  for (int i = 0; i < NumSubstrings; i++) {
     ret.push_back(str.substr(i * splitLength, splitLength));
  }
  // If there are leftover characters, create a shorter item at the end.
  if (str.length() % splitLength != 0) {
      ret.push_back(str.substr(splitLength * NumSubstrings));
  }

  return ret;
}
struct COLOR {
  short r;
  short g;
  short b;
};
COLOR hex2rgb(string hex) {
  COLOR color;
  if(hex.at(0) == '#') {
      hex.erase(0, 1);
  }
  while(hex.length() != 6) {
      hex += "0";
  }
  std::vector<string> colori=SplitWithCharacters(hex,2);
  color.r = stoi(colori[0],nullptr,16);
  color.g = stoi(colori[1],nullptr,16);
  color.b = stoi(colori[2],nullptr,16);
  return color;
}
int main() {
  string hexcolor;
  cout << "Insert hex color: ";
  cin >> hexcolor;
  COLOR color = hex2rgb(hexcolor);
  cout << "RGB:" << endl;
  cout << "R: " << color.r << endl;
  cout << "G: " << color.g << endl;
  cout << "B: " << color.b << endl;
  return 0;
}