简体   繁体   English

我如何将 reinterpter_cast 向量转换为 int?

[英]How do i reinterpter_cast vector to int?

I've got a vector of four bytes: std::vector<int8_t> src = { 0x0, 0x0, 0x0, 0xa };我有一个四个字节的向量: std::vector<int8_t> src = { 0x0, 0x0, 0x0, 0xa }; , which in hexadecimal is. , 以十六进制表示。 (0x0000000a) (0x0000000a)

How do i type-pun it into an int32_t so that i get 10 using reinterpret_cast ?我如何将它输入到int32_t以便使用reinterpret_cast得到 10?

This can be done easily using bitshifts like this:这可以使用像这样的位移轻松完成:

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

but as far as i'm aware of how reinterpret_cast work, it can be used here at its best, but i can't firgure out how exactly do that in code itself.但据我所知reinterpret_cast是如何工作的,它可以在最好的情况下在这里使用,但我无法弄清楚代码本身是如何做到这一点的。

reinterpret_cast<int32_t*>(&0x0000000a);

ps: This is not just for int32_t or so, this can be reinterpreted to anything i would wish. ps:这不仅适用于 int32_t 左右,这可以重新解释为我希望的任何内容。 That's the point.这才是重点。

This is not possible;这不可能; an attempt would be undefined behaviour due to strict aliasing violation.由于严格的别名违规,尝试将是未定义的行为。 An array of int8_t cannot be accessed as some other type (except for this specific cases listed in the rule, such as uint8_t ). int8_t数组不能作为其他类型访问(规则中列出的这种特定情况除外,例如uint8_t )。

Using bitshifts or memcpy are correct ways (as is the idea of SM's answer)使用 bitshifts 或 memcpy 是正确的方法(就像 SM 的答案一样)

#include <iostream>
#include <numeric>
#include <vector>

int main() {
  std::vector<int8_t> src = { 0x0, 0x0, 0x27, 0x10 };
  std::cout <<
    std::accumulate(src.begin(), src.end(),  // or src.begin() + sizeof(int32_t)
       0, [](const uint32_t &a, const uint8_t &b){ return a * 256 + b; });
  std::cout << std::endl;
  return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM