转换向量< unsigned char>到矢量<无符号短> [英] Convert a vector<unsigned char> to vector<unsigned short>
本文介绍了转换向量< unsigned char>到矢量<无符号短>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我从二进制文件获取数据,从文件读取并写入unsigned char的向量。我不能编辑它,因为我使用外部库。
I'm getting data from a binary file, reading from file and writing in a vector of unsigned char. I can't edit it, because I'm using a external library.
但我从文件读取的数据是一个16位图像,我想把数据放在一个无符号短
But the data that I'm reading from file is a 16 bits image, and I'd like to put the data in a vector of unsigned short
也许我可以做一个演员吗?
Maybe I can do a cast for it?
Rgds。
推荐答案
:
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
typedef unsigned char u8;
typedef unsigned short u16;
u16 combine_two_bytes(u8 a, u8 b) {
return a | (b << 8);
}
template<typename InIter, typename OutIter, typename InT, typename OutT>
void combine_pairs(InIter in, InIter in_end, OutIter out, OutT (*func)(InT, InT)) {
while(1) {
if(in == in_end) {
break;
}
InT &left = *in++;
if(in == in_end) {
break;
}
InT &right = *in++;
*out++ = func(left, right);
}
}
int main() {
using namespace std; // lazy
u8 input[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
const size_t in_size = sizeof(input) / sizeof(*input);
u16 output[in_size / 2];
cout << "Original: ";
copy(input, input + in_size, ostream_iterator<int>(cout, " "));
cout << endl;
combine_pairs(input, input + in_size, output, combine_two_bytes);
cout << "Transformed: ";
copy(output, output + in_size / 2, ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
这篇关于转换向量< unsigned char>到矢量<无符号短>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文