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?
相关问题
- Sorting 3 numbers without branching [closed]
- How to compile C++ code in GDB?
- Why does const allow implicit conversion of refere
- thread_local variables initialization
- What uses more memory in c++? An 2 ints or 2 funct
相关文章
- Class layout in C++: Why are members sometimes ord
- How to mock methods return object with deleted cop
- Which is the best way to multiply a large and spar
- C++ default constructor does not initialize pointe
- Selecting only the first few characters in a strin
- What exactly do pointers store? (C++)
- Converting glm::lookat matrix to quaternion and ba
- What is the correct way to declare and use a FILE
If you don't want to care about big/little endian, you can use:
v[0]*0x100+v[1]
Well, one other way to do it is to wrap a call to memcpy:
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!
Please use the shift operator / bit-wise operations.
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).
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];
?You may do: