简体   繁体   English

如何转换矢量 <unsigned char> 到int?

[英]How to convert vector<unsigned char> to int?

I have vector<unsigned char> filed with binary data. 我有二进制数据的vector<unsigned char> I need to take, lets say, 2 items from vector(2 bytes) and convert it to integer. 我需要从矢量(2个字节)中取出2个项目并将其转换为整数。 How this could be done not in C style? 如何做到这一点不是用C风格?

You may do: 你可能会这样做:

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

Please use the shift operator / bit-wise operations. 请使用移位运算符/逐位运算。

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

All the solutions proposed here that are based on casting/unions are AFAIK undefined behavior, and may fail on compilers that take advantage of strict aliasing (eg GCC). 此处提出的所有基于转换/联合的解决方案都是AFAIK未定义的行为,并且可能在利用严格别名 (例如GCC)的编译器上失败。

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

Well, one other way to do it is to wrap a call to memcpy: 好吧,另一种方法是将调用包装到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;
}

The extract function template also works with double, long int, float and so on. 提取函数模板也适用于double,long int,float等。

There are no size checks in this example. 此示例中没有大小检查。 We assume v actually has enough elements before each call to extract . 我们假设v在每次调用提取之前实际上有足够的元素。

Good luck! 祝好运!

what do you mean "not in C style"? 你是什​​么意思“不是C风格”? Using bitwise operations (shifts and ors) to get this to work does not imply it's "C style!" 使用按位运算(shift和ors)来实现这一点并不意味着它是“C风格!”

what's wrong with: int t = v[0]; t = (t << 8) | v[1]; 有什么问题: int t = v[0]; t = (t << 8) | v[1]; int t = v[0]; t = (t << 8) | v[1]; ?

If you don't want to care about big/little endian, you can use: 如果你不想关心大/小端,你可以使用:

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]));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM