加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 将4字节整数放入向量的前4个char元素中

发布时间:2020-12-16 10:43:50 所属栏目:百科 来源:网络整理
导读:我有一个向量 unsigned char并希望将4字节的整数放入前4个元素中. 在C中是否有比这更简单的方法: myVector.at(0) = myInt 0x000000FF;myVector.at(1) = myInt 0x0000FF00;myVector.at(2) = myInt 0x00FF0000;myVector.at(3) = myInt 0xFF000000; 解决方法
我有一个向量< unsigned char>并希望将4字节的整数放入前4个元素中.
在C中是否有比这更简单的方法:

myVector.at(0) = myInt & 0x000000FF;
myVector.at(1) = myInt & 0x0000FF00;
myVector.at(2) = myInt & 0x00FF0000;
myVector.at(3) = myInt & 0xFF000000;

解决方法

保证std :: vector存储为一个连续的数据块(& ddagger;).因此,可以处理std :: vector< unsigned char>基本上与unsigned char缓冲区相同.这意味着,只要您确定数据足够大,就可以将数据存储到矢量中:

#include <vector>
#include <cstring>
#include <cstdint>

int main()
{
  std::int32_t k = 1294323;
  std::vector<unsigned char> charvec;

  if (charvec.size() < sizeof(k))
    charvec.resize(sizeof(k));

  std::memcpy(charvec.data(),&k,sizeof(k));

  return 0;
}

注意:std :: vector的data()函数将void *返回给向量的内部缓冲区.它在C 11中可用 – 在早期版本中,可以使用向量的第一个元素的地址,& charvec [0].

当然这是使用std :: vector的一种非常不寻常的方式,并且(由于必要的resize())有点危险.我相信你有充分的理由想要这样做.

(& ddagger;)或者,正如标准所说:

(§23.3.6.1/1) […] The elements of a vector are stored contiguously,meaning that if v is a vector<T,Allocator> where T is some type other than bool,then it obeys the identity

06001

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读