|
-
December 2nd, 2009, 05:58 PM
#1
Convert vector<byte> to vector<short>?
Hi all,
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;
}
//---------------------------------------------------------------------------
Yields
0100 0302 0504 0706 0908 0b0a 0d0c 0f0e 1110
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|