我读过reinterpret_cast<>如果使用不当可能会有危险.所以我相信我正确使用它;).如果我需要模板类并且需要类型转换,我发现使用它是很好的.但最近我读到这reinterpret_cast<>也是非便携式的.我为这一点感到难过.什么原因?请使用以下代码,
void Disp(int* val)
{
for (int i=0; i < SZ; ++i)
{
cout << *(val+i) << " ";
}
cout << endl;
}
int main()
{
int arr[SZ];
Disp(arr);
unsigned char* ptr = reinterpret_cast<unsigned char*>(arr);
for (unsigned char* i = ptr; i < (ptr + (SZ * sizeof(int))); i++)
{
*i = 0;
}
Disp(arr);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
现在输出:
1174214872 32767 4196789 0 568392584 58 4196720 0 0 0
0 0 0 0 0 0 …Run Code Online (Sandbox Code Playgroud) 我的应用程序需要在 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。请提出一个解决方案。谢谢您的帮助。