std::vector<uint8_t> v(4);
uint16_t cafe = 0xCAFE;
uint16_t babe = 0xBABE;
v[0] = cafe;
v[2] = babe;


我要的行为将导致:

v[0] == 0xCA
v[1] == 0xFE
v[2] == 0xBA
v[3] == 0xBE


但是我得到了:

v[0] == 0xFE
v[1] == 0x00
v[2] == 0xBE
v[3] == 0x00


我应该怎么做才能得到想要的结果?

最佳答案

您的代码无效的原因是c ++将值转换为uint8_t,即向量所保存的类型:

v[0] = (uint8_t)cafe; // conceptually


要么

v[0] = (uint8_t)(cafe & 0xff); // conceptually


以下将执行您想要的操作:

v[0] = (uint8_t)((cafe >> 8) & 0xff);
v[1] = (uint8_t)((cafe >> 0) & 0xff);
v[2] = (uint8_t)((babe >> 8) & 0xff);
v[3] = (uint8_t)((babe >> 0) & 0xff);


如果您使用的是大端机,则不要介意代码不可移植,并希望进行一些极端的性能优化,请执行以下操作:

*(uint16_t)&v[0] = cafe;
*(uint16_t)&v[2] = babe;

08-16 08:26