首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 字符串實戰:十六進制顏色字符串轉 RGB 與整數

     編輯:關於C++

C++ 字符串實戰:十六進制顏色字符串轉 RGB 與整數

實戰中常遇到服務器返回十六進制顏色字符串(如 "#ffceed"),需轉為整數或 RGB 分量供界面使用。本文對比 Java/C++ 實現,展示 C++ 流操作優雅性。


場景 1:Hex String 轉整數顏色值

Java 寫法(Android 源碼風格):

public static int parseColor(String colorString) {
    if (colorString.charAt(0) == '#') {
        long color = Long.parseLong(colorString.substring(1), 16);
        if (colorString.length() == 7) color |= 0xFF000000;  // 補全 Alpha
        return (int) color;
    }
    // ... 顏色名稱映射
}

C++ 流操作法(推薦):

#include 
#include 

DWORD hexStringToColor(const std::string& hexStr) {
    std::string s = hexStr;
    if (!s.empty() && s[0] == '#') s.erase(0, 1);  // 去除 #
    if (s.length() == 6) s = "FF" + s;             // 補全 Alpha (ARGB)
    
    DWORD color;
    std::stringstream ss;
    ss << std::hex << s;
    ss >> std::hex >> color;
    return color;
}

// 使用
btn1->SetBkColor(hexStringToColor("#ffceed"));
btn2->SetBkColor(0xff123456);  // 直接十六進制字面量

C++ strtoul 法(C 風格,高性能):

#include 

DWORD hexStringToColor2(const std::string& hexStr) {
    std::string s = hexStr;
    if (!s.empty() && s[0] == '#') s.erase(0, 1);
    if (s.length() == 6) s = "FF" + s;
    
    return static_cast(std::strtoul(s.c_str(), nullptr, 16));
}

場景 2:Hex String 轉 RGB 三分量

#include 
#include 
#include 

void hexToRGB(const std::string& hexCode, int& r, int& g, int& b) {
    std::string s = hexCode;
    if (!s.empty() && s[0] == '#') s.erase(0, 1);
    
    std::istringstream(s.substr(0, 2)) >> std::hex >> r;
    std::istringstream(s.substr(2, 2)) >> std::hex >> g;
    std::istringstream(s.substr(4, 2)) >> std::hex >> b;
}

// 測試
int main() {
    int r, g, b;
    hexToRGB("#ffceed", r, g, b);
    std::cout << "RGB: (" << r << ", " << g << ", " << b << ")\n";  // (255, 206, 237)
    return 0;
}

核心要點總結

  • 流操作優雅:stringstream + std::hex 格式化輸入/輸出,類型安全、可擴展
  • strtoul 高效:C 標準庫函數,第三參數 base=16 直觀,適合性能敏感場景
  • 工程建議:生產代碼中避免直接 cout/printf 調試,應用日誌框架;十六進制字面量 0xFF123456 可直接用於代碼常量
  • 格式兼容:處理 #RRGGBB、#AARRGGBB、大小寫混合等變體

C++ 標準庫提供了豐富的字符串與數值轉換工具,善用 <sstream>、<cstdlib> 能寫出簡潔健壯的解析代碼。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved