簡體   English   中英

用十六進制值編碼std :: string

[英]Encode std::string with hex values

我的應用程序需要在std :: string中編碼和傳輸一些十六進制值。 所以我就是這樣。

static string printHex(const string& str)
{
    stringstream ss;
    ss << "[ " << hex;
    for (int i = 0; i < str.size(); i++)
    {
        ss << (((uint32_t)str[i] )& 0xFF) << " ";
    }
    ss << "]" << dec;

    return ss.str();
}

int main()
{
    char ptr[] = {0xff, 0x00, 0x4d, 0xff, 0xdd};// <--see here, 0x00 is the issue.
    string str(ptr);
    cout << printHex(str) << endl;
    return 0;
}

顯然,該字符串僅采用最多0x00的值,其余數據丟失。 如果沒有0x00,它將適用於任何值。 但我也需要0x00。 請提出解決方案。 謝謝您的幫助。

從數組的整個范圍構造字符串:

std::string str(std::begin(ptr), std::end(ptr));   // C++11
std::string str(ptr, ptr + sizeof ptr);            // Historical C++

請注意,這僅在ptr實際上是數組而不是指針的情況下有效。 如果只有一個指針,則無法知道它指向的數組的大小。

您應該考慮使用ptr以外的其他名稱來調用數組,這意味着它可能是指針。

另外,在C ++ 11中,您可以在不需要數組的情況下對字符串進行列表初始化:

std::string str {0xff, 0x00, 0x4d, 0xff, 0xdd};

暫無
暫無

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

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