給定 CString a = "1A 2B",需將每兩個十六進制字符轉為一個字節,存入另一個 CString 或 char*。
CString HexStrToText(const CString& hexStr)
{
// 1. 清理空格
CString clean = hexStr;
clean.Remove(' '); // 也可 Remove('\t') 等
if (clean.GetLength() % 2 != 0)
return _T(""); // 長度必須為偶數
// 2. 輸出緩衝區
int outLen = clean.GetLength() / 2;
CStringA result; // ANSI 字符串接收字節
result.GetBufferSetLength(outLen);
char* pOut = result.GetBuffer();
// 3. 輔助轉換 Lambda
auto charToVal = [](TCHAR ch) -> int {
if (ch >= _T('0') && ch <= _T('9')) return ch - _T('0');
if (ch >= _T('A') && ch <= _T('F')) return ch - _T('A') + 10;
if (ch >= _T('a') && ch <= _T('f')) return ch - _T('a') + 10;
return -1; // 非法字符
};
// 4. 逐對轉換
LPCTSTR pIn = clean;
for (int i = 0; i < outLen; ++i) {
int high = charToVal(pIn[i * 2]);
int low = charToVal(pIn[i * 2 + 1]);
if (high < 0 || low < 0) { result.ReleaseBuffer(); return _T(""); }
pOut[i] = static_cast((high << 4) | low);
}
result.ReleaseBuffer(outLen);
return CString(result); // 隱式轉為 CString (視項目字符集而定)
}
| 環節 | 注意事項 |
|---|---|
| 字符集 | 項目為 Unicode 時,CString 存 wchar_t,轉換後字節建議存 CStringA 或 std::string |
| 異常處理 | 非法字符、奇數長度、空指針需防御 |
| 性能 | 預分配緩衝區、避免逐字符拼接 |
CString input = _T("1A 2B 3C 4D");
CString output = HexStrToText(input);
// output 內部字節為 {0x1A, 0x2B, 0x3C, 0x4D}
// 若需顯示可再轉為十六進制 Dump
CString TextToHexStr(const BYTE* data, int len)
{
CString hex;
for (int i = 0; i < len; ++i)
hex.AppendFormat(_T("%02X "), data[i]);
return hex.TrimRight(); // "1A 2B 3C 4D"
}
掌握十六進制字符串與二進制數據互轉,是嵌入式/網絡/協議開發的基礎技能。