mthoutai

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

非常久没有写关于string的博客了。由于写的差点儿相同了。可是近期又与string打交道,于是荷尔蒙上脑,小蝌蚪躁动。

在程序中,假设用到了颜色代码,一般都是十六进制的,即hex。

可是server给你返回一个颜色字符串。即hex string

你怎么把这个hex string 转为 hex,并在你的代码中使用?

更进一步,你怎么办把一个形如”#ffceed”的hex string 转为 RGB呢?

第一个问题在Java中是这样搞的:

public static int parseColor(@Size(min=1) String colorString) {
if (colorString.charAt(0) == '#') {
// Use a long to avoid rollovers on #ffXXXXXX
long color = Long.parseLong(colorString.substring(1), 16);
if (colorString.length() == 7) {
// Set the alpha value
color |= 0x00000000ff000000;
} else if (colorString.length() != 9) {
throw new IllegalArgumentException("Unknown color");
}
return (int)color;
} else {
Integer color = sColorNameMap.get(colorString.toLowerCase(Locale.ROOT));
if (color != null) {
return color;
}
}
throw new IllegalArgumentException("Unknown color");
}

可是在C++中,我们能够用流,这样更加简洁:

    auto color_string_iter = hex_string_color.begin();
    hex_string_color.erase(color_string_iter);
    hex_string_color= "ff" + hex_string_color;
    DWORD color;
    std::stringstream ss;
    ss << std::hex << hex_string_color;
    ss >> std::hex >> color;

    btn1->SetBkColor(color);
    btn2->SetBkColor(0xff123456);

还有一种方法,能够使用:std::strtoul
主要是第三个參数:
Numerical base (radix) that determines the valid characters and their interpretation.
If this is 0, the base used is determined by the format in the sequence

#include <cstdlib>
#include <iostream> // for std::cout

int main()
{
    char hex_string[] = "0xbeef";
    unsigned long hex_value
        = std::strtoul(hex_string, 0, 16);
    std::cout << "hex value: " << hex_value << std::endl;
    return 0;
}

接下来看看怎样把hex string 转rgb:

#include <iostream>
#include <sstream>

int main()
{
   std::string hexCode;
   std::cout << "Please enter the hex code: ";
   std::cin >> hexCode;

   int r, g, b;

   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';
}

这里有一点忠告,也是忠告自己。
我们从学习编程開始,最熟悉的就是print或是cout看看结果。可是在实际工作中是非常少用到的。

比方有一个十进制数100。我们何以通过cout<

posted on 2017-07-23 08:08  mthoutai  阅读(10436)  评论(0编辑  收藏  举报