首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 更多程式語言 >> 程式設計綜合問答

C++ 將 rdbuf() 輸出的二進位資料轉為可讀十六進位或 Base64

     編輯:程式設計綜合問答

需求

使用 `sourceFile.rdbuf()` 讀取二進位檔案並輸出,結果顯示亂碼。需轉為可識別的十六進位或 Base64 字串,且可逆向還原。

方案一:Base64 編碼(推薦,體積增長 33%)

#include 
#include 
#include 
// 需自行實現或使用庫:OpenSSL、Boost、C++23 std::base64
std::string base64_encode(const std::vector& data);

int main() {
    std::ifstream file("binary.dat", std::ios::binary);
    std::vector buffer((std::istreambuf_iterator(file)), {});
    
    std::string b64 = base64_encode(buffer);
    std::cout << b64; // 可安全存為文字檔、傳輸 JSON、XML
    
    // 還原
    std::vector decoded = base64_decode(b64);
    std::ofstream out("restored.dat", std::ios::binary);
    out.write(reinterpret_cast(decoded.data()), decoded.size());
}

方案二:十六進位字串(體積增長 100%,直觀)

std::string to_hex(const std::vector& data) {
    static const char* hex = "0123456789ABCDEF";
    std::string result;
    result.reserve(data.size() * 2);
    for (unsigned char b : data) {
        result.push_back(hex[b >> 4]);
        result.push_back(hex[b & 0xF]);
    }
    return result;
}

std::vector from_hex(const std::string& hexStr) {
    std::vector data;
    data.reserve(hexStr.size() / 2);
    for (size_t i = 0; i < hexStr.size(); i += 2) {
        unsigned char high = (hexStr[i] >= 'A') ? (hexStr[i] - 'A' + 10) : (hexStr[i] - '0');
        unsigned char low  = (hexStr[i+1] >= 'A') ? (hexStr[i+1] - 'A' + 10) : (hexStr[i+1] - '0');
        data.push_back((high << 4) | low);
    }
    return data;
}

方案三:直接處理二進位流(無需轉碼)

若只需複製檔案:

std::ifstream src("in.dat", std::ios::binary);
std::ofstream dst("out.dat", std::ios::binary);
dst << src.rdbuf(); // 高效、無轉換、完美還原

選擇建議

場景推薦格式理由
JSON/XML/資料庫文字欄位存儲Base64標準化、單行、URL 安全變體可用
除錯、日誌、人工檢視Hex直觀、易對照位元組
檔案複製、網路傳輸二進位協議原始二進位零開銷、最高效

現代 C++ 庫推薦

  • Base64:cpp-base64(單頭文件)、Boost.Beast、C++23 `std::base64`(提案中)。
  • Hex:hex、Boost.Algorithm (`boost::algorithm::hex`)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved