實戰中常遇到服務器返回十六進制顏色字符串(如 "#ffceed"),需轉為整數或 RGB 分量供界面使用。本文對比 Java/C++ 實現,展示 C++ 流操作優雅性。
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));
}
#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> 能寫出簡潔健壯的解析代碼。