c++ - 我如何将 vector reinterpret_cast 转换为int?

标签 c++ casting reinterpret-cast

我有一个四个字节的 vector : std::vector<int8_t> src = { 0x0, 0x0, 0x0, 0xa }; ,十六进制表示为。 (0x0000000a)

我如何将其双关语输入 int32_t这样我就可以使用 reinterpret_cast 得到 10 ?

这可以使用如下位移位轻松完成:

(int32_t)((src[offset] << 24) | (src[offset+ 1] << 16) | (src[offset+ 2] << 8) | (src[offset+ 3]));

但据我所知reinterpret_cast工作,它可以在这里得到最好的使用,但我无法弄清楚在代码本身中到底如何做到这一点。

reinterpret_cast<int32_t*>(&0x0000000a);

ps:这不仅仅适用于 int32_t 左右,它可以重新解释为我想要的任何内容。这就是重点。

最佳答案

这是不可能的;由于严格的别名冲突,尝试将是未定义的行为。 int8_t 数组无法作为其他类型进行访问(规则中列出的特定情况除外,例如 uint8_t)。

使用 bitshifts 或 memcpy 是正确的方法(正如 S.M. 的答案的想法)

关于c++ - 我如何将 vector reinterpret_cast 转换为int?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60236234/

相关文章:

c - int 指针类型为 int

指定类型时 javac "uses unchecked or unsafe operations"

java - javac 完成的任何类型转换?

C++ 从事件处理程序中获取数据并传递给另一个类的方法?

c++ - 使用 qmultimedia 低级 API 的 Qt 中的音频输出问题

c++ - 在方法中返回静态变量是个坏主意吗?

c++ - 什么时候使用 reinterpret_cast 而不违反严格的别名规则?

c++ - reinterpret_cast 与 static_cast 用于在标准布局类型中写入字节?

C++ reinterpret_cast 对 std::shared_ptr 引用进行优化

c++ - 是否可以从大型固定宽度 CSV 文件中有效获取行的子集?