簡體   English   中英

如何將 uint8_t 的向量轉換為 C++ 中的 std::string?

[英]How to convert vector of uint8_t into std::string in C++?

我正在嘗試將字節正確轉換為字符串。 但是轉換后的字符串看起來像垃圾。 我有以下代碼:

#include <iostream>
#include <sstream>
#include <vector>

 std::string HexString( std::vector<std::uint8_t> &bytes ) {
                std::stringstream ss;
                for ( std::int32_t i = 0; i < bytes.size(); i++ ) {
                    if(i != 0)
                        ss << ",";
                    ss << bytes[i];
                }
                return ss.str();
}

int main() {
    std::vector<uint8_t> uuid = {
                 0x41,0x7c, 0xea, 0x9a,0xaf
    };
    
    std::string uuidString = HexString(uuid);
    
    std::cout << "Should be equal" << std::endl;
    std::cout << uuidString << std::endl;
    std::cout << "0x41, 0x7c, 0xea, 0x9a, 0xaf" << std::endl;

    return 0;
}

Output:

Both should be equal:
A,|,�,�,�
0x41, 0x7c, 0xea, 0x9a, 0xaf

正確的 output 應該是:

Both should be equal:
0x41, 0x7c, 0xea, 0x9a, 0xaf
0x41, 0x7c, 0xea, 0x9a, 0xaf

任何建議,將不勝感激。

  • 您的uint8_t值被解釋為字符。 將它們轉換為整數以進行 stream 操作
  • 對 stream 操作使用std::hex將整數轉換為十六進制表示
  • 添加“0x”,因為std::hex不會為您執行此操作。
  • 在逗號后添加一個空格
std::string HexString(std::vector<std::uint8_t> &bytes)
{
    std::stringstream ss;
    for (std::size_t i = 0; i < bytes.size(); i++)
    {
        if (i != 0)
        {
            ss << ", ";
        }
        ss << "0x" << std::hex << static_cast<int>(bytes[i]);
    }
    return ss.str();
}

有了這個,我得到:

Should be equal
0x41, 0x7c, 0xea, 0x9a, 0xaf
0x41, 0x7c, 0xea, 0x9a, 0xaf

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM