c++ - 我可以将 unsigned char* 转换为 unsigned int* 吗?

标签 c++ memory-management static-cast

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/

相关文章:

c++ - 设置 DirectX9 表面像素

c++ - Poco FIFOBuffer read() 错误

c++ - 跨 DLL 边界 vector 的内存重定位

c# - 解决调用DrawImage时出现 'Out of memory'异常

C# 评估 13 位而不是 native 16 位的开销

c++ - 为什么我不能使用 static_cast<const char**>(str) 而不是 (const char**)str?

c++ - 使用指向对象的指针 vector 进行 boost (C++ - linux)

c++ - 在 NULL 指针上调用 delete - C++03 与 C++11

c++ - 我需要 static_cast 我的数字模板值吗?

c++ - static_cast 为不同的类型,并 move 结果