现在我正在以这种方式将 int 转换为字节数组:
int num = 16777215;
char* bytes = static_cast<char*>(static_cast<void*>(&num));
这是最好的方法吗?
另外,如何从该数组中检索 int 值?
最佳答案
如果你想要字节,你使用了错误的转换:
char* bytes = reinterpret_cast<char*>(&num);
反之亦然:
int num = *reinterpret_cast<int*>(bytes);
请注意,通常您不能这样做,char
是特殊的,因此您可能需要查找别名。
关于c++ - 在 C++ 中从字节数组检索整数的最佳方法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26964601/