使用十六进制值对 std::string 进行编码

sar*_*ath 1 c++

我的应用程序需要在 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;
}
Run Code Online (Sandbox Code Playgroud)

显然,该字符串仅获取 0x00 以内的值,其余数据都会丢失。如果没有 0x00,它将适用于任何值。但我也需要 0x00。请提出一个解决方案。谢谢您的帮助。

Mik*_*our 5

从数组的整个范围构造字符串:

std::string str(std::begin(ptr), std::end(ptr));   // C++11
std::string str(ptr, ptr + sizeof ptr);            // Historical C++
Run Code Online (Sandbox Code Playgroud)

ptr请注意,这仅在实际上是数组而不是指针时才有效。如果只有一个指针,则无法知道它指向的数组的大小。

您应该考虑将该数组称为 以外的名称ptr,这意味着它可能是一个指针。

或者,在 C++11 中,您可以列表初始化字符串而不需要数组:

std::string str {0xff, 0x00, 0x4d, 0xff, 0xdd};
Run Code Online (Sandbox Code Playgroud)