How to convert vector to int?

2020-03-24 05:27发布

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

6条回答
▲ chillily
2楼-- · 2020-03-24 06:00

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]));
查看更多
beautiful°
3楼-- · 2020-03-24 06:02

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

查看更多
Deceive 欺骗
4楼-- · 2020-03-24 06:03

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!

查看更多
何必那么认真
5楼-- · 2020-03-24 06:06

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).

查看更多
Luminary・发光体
6楼-- · 2020-03-24 06:10

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

查看更多
成全新的幸福
7楼-- · 2020-03-24 06:16

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
查看更多
登录 后发表回答