簡體   English   中英

將 std::array 字節轉換為十六進制 std::string

[英]convert std::array of bytes to hex std::string

我想要一種方法來獲取任意大小的字節數組並返回一個十六進制字符串。 專門用於記錄通過網絡發送的數據包,但我使用了大量采用 std::vector 的等效函數。 像這樣的東西,可能是模板?

std::string hex_str(const std::array<uint8_t, ??? > array);

我已經搜索過,但解決方案都說“將其視為 C 風格的數組”,我特別問是否有辦法不這樣做。 我認為這不是在每個 C++ FAQ 中的原因是這是不可能的,如果是的話,有人可以概述原因嗎?

我已經有了這些重載,第二個可以通過衰減為 C 樣式數組來用於 std::array,所以請不要告訴我怎么做。

std::string hex_str(const std::vector<uint8_t> &data);
std::string hex_str(const uint8_t *data, const size_t size);

(編輯:vector 是我代碼中的參考)

如果您在編譯時知道std::array的大小,則可以使用非類型模板參數。

template<std::size_t N>
std::string hex_str( const std::array<std::uint8_t, N>& buffer )
{ /* Implementation */ }

int main( )
{   
    // Usage.
    std::array<std::uint8_t, 5> bytes = { 1, 2, 3, 4, 5 };
    const auto value{ hex_str( bytes ) };
}

或者,您可以僅對整個容器進行模板化(減少過載)。

template<typename Container>
std::string hex_str( const Container& buffer ) 
{ /* Implementaion */ }

int main( )
{   
    // Usage.
    std::array<std::uint8_t, 5> bytes = { 1, 2, 3, 4, 5 };
    const auto value{ hex_str( bytes ) };
}

您應該考慮編寫函數以使用迭代器,就像標准算法一樣。 然后你可以將它與std::vectorstd::array輸入一起使用,例如:

template<typename Iter>
std::string hex_str(Iter begin, Iter end)
{
    std::ostringstream output;
    output << std::hex << std::setw(2) << std::setfill('0');
    while(begin != end)
        output << static_cast<unsigned>(*begin++);
    return output.str();
}

在線演示

如果你真的想避免在你傳入的任何容器上調用begin() / end() ,你可以定義一個助手來為你處理,例如:

template<typename C>
std::string hex_str(const C &data) {
    return hex_str(data.begin(), data.end());
}

在線演示

或者,如果您真的想要,您可以將其全部壓縮為一個函數,例如:

template <typename C>
std::string hex_str(const C& data)
{
    std::ostringstream output;
    output << std::hex << std::setw(2) << std::setfill('0');
    for(const auto &elem : data)
        output << static_cast<unsigned>(elem);
    return output.str();
}

在線演示

暫無
暫無

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

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