[英]Encode std::string with hex values
My application requires some hex values to be encoded and transmitted in std::string. 我的应用程序需要在std :: string中编码和传输一些十六进制值。 So I'm doing like this.
所以我就是这样。
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;
}
Obviously the string is taking values only upto 0x00, the rest of the data is lost. 显然,该字符串仅采用最多0x00的值,其余数据丢失。 Without 0x00 it'll work for any values.
如果没有0x00,它将适用于任何值。 But I need 0x00 also.
但我也需要0x00。 Please suggest a solution.
请提出解决方案。 Thanks for the help.
谢谢您的帮助。
Construct the string from the entire range of the array: 从数组的整个范围构造字符串:
std::string str(std::begin(ptr), std::end(ptr)); // C++11
std::string str(ptr, ptr + sizeof ptr); // Historical C++
Note that this only works if ptr
is actually an array, not a pointer. 请注意,这仅在
ptr
实际上是数组而不是指针的情况下有效。 If you only have a pointer, then there's no way to know the size of the array it points to. 如果只有一个指针,则无法知道它指向的数组的大小。
You should consider calling the array something other than ptr
, which implies that it might be a pointer. 您应该考虑使用
ptr
以外的其他名称来调用数组,这意味着它可能是指针。
Alternatively, in C++11, you can list-initialise the string with no need for an array: 另外,在C ++ 11中,您可以在不需要数组的情况下对字符串进行列表初始化:
std::string str {0xff, 0x00, 0x4d, 0xff, 0xdd};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.