【问题标题】:How to cast, in C++, a byte vector (std::vector<uint8_t>) into different uint32_t, uint16_t and uint8_t variables如何在 C++ 中将字节向量 (std::vector<uint8_t>) 转换为不同的 uint32_t、uint16_t 和 uint8_t 变量
【发布时间】:2020-06-10 09:56:37
【问题描述】:

我有字节向量,std::vector,我想将它的信息提取为一些不同长度的整数。

例如,我可以有一个 7 字节的向量,我想在开头读取一个 uint32_t,然后是 uint16_t,最后是 uint8_t。我需要一种方法来指定应该从向量的哪个元素开始读取以及应该读取多少字节。

std::vector<std::uint8_t>& bytes(7);
uint32_t a;
uint16_t b;
uint8_t c;

// Could be something similar to this? 
// This yields an invalid conversion error: {aka unsigned char}’ to ‘const void*’
std::memcpy(&a, bytes[0], sizeof(uint32_t)); 
std::memcpy(&a, bytes[4], sizeof(uint16_t));
std::memcpy(&a, bytes[6], sizeof(uint8_t));

【问题讨论】:

  • 您应该小心未定义的行为等。也就是说,我记得有一种方法可以获取std::vector 的底层数组,这可能很有用,您可以在这里找到它:en.cppreference.com/w/cpp/container/vector
  • 请注意,在这种方法中,整数的字节必须在数组中的 CPU 原生字节顺序中。给定相同的数组,这将导致 CPU 上具有不同字节序的不同值。如果数据用于跨系统的序列化(例如,通过网络),这将是一个问题。
  • 你知道这种转换依赖于(正确的)endianess吗?
  • 是的,我正在考虑字节序。实际上,字节是通过网络在具有相同字节序的两个设备之间传输的。
  • 三个memcpy都在将字节复制到a。另外两个应该是bc

标签: c++ vector byte


【解决方案1】:

你可以取vector中元素的地址来实现你想要的:

std::memcpy(&a, &bytes[0], sizeof(std::uint32_t));
//              ^
//or use .data() instead
std::memcpy(&a, bytes.data() + 0, sizeof(std::uint32_t));    

【讨论】:

  • 为什么需要+ 0
  • @Evg 演示如何在索引处获取指向元素的指针。在示例中,元素位于索引 0 处。
猜你喜欢
  • 2014-07-23
  • 2022-01-09
  • 2017-06-13
  • 1970-01-01
  • 2020-12-09
  • 1970-01-01
  • 2015-09-15
  • 1970-01-01
  • 2021-07-11
相关资源
最近更新 更多