c++ - 将 vector<unsigned char> 转换为 vector<unsigned short>

标签 c++

我正在从一个二进制文件中获取数据,从文件中读取数据并写入一个无符号字符 vector 。我无法编辑它,因为我正在使用外部库。

但是我从文件中读取的数据是一个 16 位图像,我想将数据放入一个 unsigned short vector 中

也许我可以为它做一个类型转换?

研发。

最佳答案

通用方法(非防弹):

#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;
}

关于c++ - 将 vector<unsigned char> 转换为 vector<unsigned short>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1898212/

相关文章:

c++ - 从基非模板类调用派生模板类方法

c++ - consteval 函数是否允许依赖于函数参数的模板参数?

c++ - SDL2 窗口在失焦时不起作用

c++ - 窗口/对话框过程可以在 namespace 中吗?

在 Windows 上运行并生成 Linux 代码的 C++ 编译器

c++ - DirectX Index Buffer 索引顺序

c++ - 如何访问子 UI 文件

c++ - 在命名空间中安装目标

c++ - 如何在 3D 中绘制 2D 网格?

c++ - 错误 : no matching function for call to "Queue::Queue()"