Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert vector<unsigned char> to int?

Tags:

c++

stl

stdvector

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?

like image 500
Hitman_99 Avatar asked Oct 27 '10 09:10

Hitman_99


1 Answers

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

like image 195
Daniel Avatar answered Sep 30 '22 00:09

Daniel