實戰c++中的string系列--十六進制的字符串轉為十六進制的整型(一般是顏色代碼使用)


非常久沒有寫關於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<


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM