开发者

How to convert vector<unsigned char> to int?

I have vector<unsigned char> filed with binary data. I need to take, lets say, 2 items f开发者_C百科rom vector(2 bytes) and convert it to integer. How this could be done not in C style?


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 (e.g. GCC).


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


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


Well, one other way to do it is to wrap a call to 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.

There are no size checks in this example. We assume v actually has enough elements before each call to extract.

Good luck!


what do you mean "not in C style"? Using bitwise operations (shifts and ors) to get this to work does not imply it's "C style!"

what's wrong with: 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]));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜