如何将vector <unsigned char =“”>转换为int?</unsigned>

时间:2010-10-27 09:00:53

标签: c++ stl stdvector

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

6 个答案:

答案 0 :(得分: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

答案 1 :(得分:6)

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

int t = (v[0] << 8) | v[1];

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

答案 2 :(得分:5)

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

答案 3 :(得分:4)

好吧,另一种方法是将调用包装到memcpy:

#include <vector>
using namespace std;

template <typename T>
T extract(const vector<unsigned char> &v, int pos)
{
  T value;
  memcpy(&value, &v[pos], sizeof(T));
  return value;
}

int main()
{
  vector<unsigned char> v;
  //Simulate that we have read a binary file.
  //Add some binary data to v.
  v.push_back(2);
  v.push_back(1);
  //00000001 00000010 == 258

  int a = extract<__int16>(v,0); //a==258
  int b = extract<short>(v,0); //b==258

  //add 2 more to simulate extraction of a 4 byte int.
  v.push_back(0);
  v.push_back(0);
  int c = extract<int>(v,0); //c == 258

  //Get the last two elements.
  int d = extract<short>(v,2); // d==0

  return 0;
}

extract 函数模板也适用于double,long int,float等。

此示例中没有大小检查。我们假设v在每次调用 extract 之前实际上都有足够的元素。

祝你好运!

答案 4 :(得分:3)

你是什么意思“不是C风格”?使用按位运算(shift和ors)来实现这一点并不意味着它是“C风格!”

出了什么问题:int t = v[0]; t = (t << 8) | v[1];

答案 5 :(得分:1)

如果您不想关心大/小端,可以使用:

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

int i = ntohs(*reinterpret_cast<const uint16_t*>(&somevector[0]));
相关问题