如何将vector <unsigned char>转换为int?

Hit*_*_99 4 c++ stl stdvector

我已vector<unsigned char>提交二进制数据.我需要从矢量(2个字节)中取出2个项目并将其转换为整数.如何做到这一点不是用C风格?

ere*_*eOn 6

你可能会这样做:

vector<unsigned char> somevector;
// Suppose it is initialized and big enough to hold a uint16_t

int i = *reinterpret_cast<const uint16_t*>(&somevector[0]);
// But you must be sure of the byte order

// or
int i2 = (static_cast<int>(somevector[0]) << 8) | somevector[1];
// But you must be sure of the byte order as well
Run Code Online (Sandbox Code Playgroud)


Dan*_*iel 6

请使用移位运算符/逐位运算.

int t = (v[0] << 8) | v[1];
Run Code Online (Sandbox Code Playgroud)

此处提出的所有基于转换/联合的解决方案都是AFAIK未定义的行为,并且可能在利用严格别名(例如GCC)的编译器上失败.

  • 你能解释一下这是怎么回事吗?换档操作中8的意义何在?如果我将它用于long long类型而不是int类型,那么这个表达式如何变化? (3认同)
  • 当与算术或按位运算符一起使用时,小于 `int` 的类型会被提升为 int,因此移位工作正常而无需显式转换 v[0]。 (2认同)

Eug*_*ith 5

v [0]*为0x100 + V [1]