我有一个四个字节的 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/