简体   繁体   English

用std :: vector的内容初始化结构<unsigned char>

[英]Initializing a struct with the contents of a std::vector<unsigned char>

This seems like something that should be simple and straightforward, but Google turns up very little. 这看起来应该很简单明了,但Google却很少出现。

What's a clean, modern (C++11) way of initializing a simple file header struct like the following 初始化简单文件头结构的干净,现代(C ++ 11)方法是什么,如下所示

typedef struct FooHeader {
    uint8_t    FooCount;
    uint8_t    BarCount;
    uint32_t   BazOffsets[4];
} FooHeader;

with the data contained in a std::vector<unsigned char> ? 与包含在std::vector<unsigned char> Is it a good idea to create a sub vector and cast its data to the header struct type, or? 创建子向量并将其数据转换为标头struct类型是一个好主意吗?

To avoid running into packing, alignment and endianness issues, it is best to read the data at the byte level (on almost all modern hardware, you can assume 8-bit bytes, but packing often changes between compilers (or even just between different compilation flags) and both big and little endian computers are still common). 为了避免遇到打包,对齐和字节序问题,最好以字节级别读取数据(在几乎所有现代硬件上,您都可以假设8位字节,但是打包经常在编译器之间(甚至只是在不同编译之间进行更改)标志)和大小端计算机都仍然很常见)。

This means that your best bet is something like: 这意味着您最好的选择是:

FooHeader load_FooHeader(std::vector<unsigned char> const &dat) {
    static_assert(
        std::numeric_limits<unsigned char>::digits == 8,
        "Assumes 8-bit bytes");

    FooHeader retv;

    retv.FooCount = dat[0];
    retv.BarCount = dat[1];

    //Start at the fifth byte, to allow for padding.
    //If you want to use a packed format, use index = 2;
    std::size_t index{4};
    for (std::size_t i{0}, iend{4}; i < iend; ++i) {
        retv.BarOffsets[i] = 0;
        //Adjust ordering depending on desired endianness.
        //Currently uses little endian.
        for (std::size_t j{0}, jend{4}; j < jend; ++j) {
            retv.BarOffsets[i] |= dat[index + i*4 + (3-j)] << (j*8);
        }
    }

    return retv;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM