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

Windows 平台 ANSI、UTF-8 與 Unicode 互轉實作

     編輯:關於C語言

字元編碼轉換的實用工具函式

字串編碼亂碼問題困擾許多 Windows 開發者。下面提供兩個可直接使用的 C++ 函式,分別處理 UTF-8 ↔ Unicode(UTF-16)轉換,基於 Windows API MultiByteToWideChar 與 WideCharToMultiByte 實作。

UTF-8 轉 Unicode (wstring)

inline std::wstring utf8ToUnicode(const std::string& str)
{
    // 先查詢所需緩衝區大小
    size_t wcsLen = ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), 
                                          static_cast<int>(str.length()), 
                                          nullptr, 0);
    if (wcsLen == 0) return L"";

    // 配置記憶體(+1 給結尾 null)
    std::vector<wchar_t> wszString(wcsLen + 1, 0);

    // 實際轉換
    ::MultiByteToWideChar(CP_UTF8, 0, str.c_str(), 
                          static_cast<int>(str.length()), 
                          wszString.data(), static_cast<int>(wcsLen));

    return std::wstring(wszString.data());
}

Unicode 轉 UTF-8 (string)

inline std::string unicodeToUtf8(const std::wstring& wstr)
{
    int len = ::WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), 
                                    static_cast<int>(wstr.length()), 
                                    nullptr, 0, nullptr, nullptr);
    if (len == 0) return "";

    std::vector<char> szUtf8(len + 1, 0);
    ::WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), 
                          static_cast<int>(wstr.length()), 
                          szUtf8.data(), len, nullptr, nullptr);

    return std::string(szUtf8.data());
}

關鍵點說明

  • 使用 std::vector 取代手動 new/delete,避免記憶體洩漏,符合 RAII 原則。
  • 第一次呼叫 API 時傳 nullptr 取得所需緩衝區大小,第二次實際轉換。
  • CP_UTF8 明確指定代碼頁,避免系統預設值造成不可預期行為。
  • 原始碼中 delete wszString 應為 delete[] wszString,現代化寫法直接用容器更安全。

適用場景

  • 讀寫 UTF-8 編碼的設定檔、JSON、XML
  • 網路傳輸資料編碼轉換
  • 與僅支援 Unicode API 的庫互動
  • 跨平台專案在 Windows 端的編碼適配層

來源:ccSec | cc@insight-labs.org

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