I'd like a code-concise way to find a modulo (2^16) sum of a vector<uint8_t>. i.e. The bytes are grabbed in pairs, and summed into an unsigned short (uint16_t). I tried making a vector<uint16_t> from the vector<uint8_t> using reinterpret_cast and the vector constructor that takes iterators (third one here http://www.cplusplus.com/reference/stl/vector/vector/)...figuring I could then use the accumulate algorithm...but the bytes were swapped (wrong endianness, I guess).
Thoughts?
Thanks.
Code:
//---------------------------------------------------------------------------
#include <vector>
#include <iostream>
#include <iomanip>
#include <stdint>
#pragma hdrstop
using std::vector;
using std::cout;
//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char* argv[])
{
vector<uint8_t> byteVec;
for (uint8_t b=0; b<0x12; b++)
byteVec.push_back(b);
//vector<uint16_t> shortVec(byteVec);
typedef vector<uint16_t>::iterator iter_t;
iter_t begin = reinterpret_cast<iter_t>(byteVec.begin());
iter_t end = reinterpret_cast<iter_t>(byteVec.end());
vector<uint16_t> shortVec(begin, end);
//cout << std::hex << std::setw(4) << std::setfill('0');
for (iter_t it=shortVec.begin(); it != shortVec.end(); it++) {
cout << std::hex << std::setw(4) << std::setfill('0') << *it << ' ';
}
return 0;
}
//---------------------------------------------------------------------------
Firstly, a vector<uint8_t> and a vector<uint16_t> are two totally different types -- one is an elephant and the other an albatross. Just because they use the same template class doesn't change that fact.
Calling reinterpret_cast on them is implementation-defined behaviour and not portable.
More computing sins are committed in the name of efficiency (without necessarily achieving it) than for any other single reason - including blind stupidity. --W.A.Wulf
Premature optimization is the root of all evil --Donald E. Knuth
See attached for an approach that provides a byte-order-agnostic internal buffer, which just stores a current value as an array of bytes. The class also provides an interface for setting/getting bit-ranges. It also allows you to specify the byte-order of the integer that is passed to the setBits(), as well as the byte-order required for the value that we return from getBits() method.
I'd love to improve this code to use insertion and extraction operators i.e operator>> and operator<< - while retaining the same functionality but my expertise is not there yet. A user here may already have an approach that uses insertion and extraction operators
* The Best Reasons to Target Windows 8
Learn some of the best reasons why you should seriously consider bringing your Android mobile development expertise to bear on the Windows 8 platform.