简体   繁体   English

如何使用位域将数据从二进制文件复制到结构中?

[英]How to use bit-fields in order to copy data into a struct from a binary?

I have a binary file that I am trying to extract data from. 我有一个试图从中提取数据的二进制文件。 The last 5 data points int the file are 10 bit integer types and I am struggling on how to extract that information and convert it into something readable. 文件中的最后5个数据点是10位整数类型,我在如何提取该信息并将其转换为可读的内容方面感到吃力。 I have tried the following code: 我尝试了以下代码:

struct bitField
{
    unsigned value: 10;
};

struct Data
{
    bitField x;
}

int main()
{
    std::array<char,696> buffer;
    std::ifstream file ("file.bin", std::ios::in | std::ios::binary);
    file.read(buffer.data(),buffer.size());

    Data a;

    std::memcpy(&a.x.value,&buffer[612],sizeof(struct bitField));

}

I am then met with the error attempt to take address of bit-field . 然后我遇到了attempt to take address of bit-field的错误attempt to take address of bit-field I have then tried using std::bitset<10> in place of bitField in my Data struct. 然后,我已经尝试使用std::bitset<10>代替位域在我的数据结构。 And while I do not get a compiler error, I get back a bunch of 0's instead which I believe is incorrect data. 虽然我没有遇到编译器错误,但我还是得到了一堆0,我认为这是不正确的数据。

How do you properly read in the data? 您如何正确读取数据?

You can't take an address of a bit-field value as it may not be byte-aligned. 您不能使用位字段值的地址,因为它可能没有字节对齐。 You should copy directly into ax (not axvalue). 您应该直接复制到ax(而不是axvalue)中。

Further, you don't really need to have a separate bitfield struct. 此外,您实际上并不需要单独的位域结构。 You can simply put bitfields right into Data struct. 您只需将位域直接放入Data结构中即可。

See this on how to use bitfields: https://www.geeksforgeeks.org/bit-fields-c/ 有关如何使用位域的信息,请参见: https//www.geeksforgeeks.org/bit-fields-c/

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

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