error: invalid static_cast from type ‘unsigned char*’ to type ‘uint32_t* {aka unsigned int*}’
uint32_t *starti = static_cast<uint32_t*>(&memory[164]);
我分配了一个字符数组,我想将 4 个字节作为 32 位 int 读取,但出现编译器错误。 我知道我可以像这样移位:
(start[0] << 24) + (start[1] << 16) + (start[2] << 8) + start[3];
它会做同样的事情,但这是很多额外的工作。
是否可以通过某种方式将这四个字节转换为 int?
最佳答案
static_cast
旨在用于“行为良好”的转换,例如 double -> int
。
您必须使用 reinterpret_cast
:
uint32_t *starti = reinterpret_cast<uint32_t*>(&memory[164]);
或者,如果你愿意,C 风格的转换:
uint32_t *starti = (uint32_t*)&memory[164];
关于c++ - 我可以将 unsigned char* 转换为 unsigned int* 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22770255/