0

I am trying to read a file as binary using fstream into a structure. This file contains normally aligned values as well as 12 and 9 bit values following this schematic: bitfield schematics My structure looks like this:

struct sFile{
    unsigned char padding1[765]; //other values before this
    char identifier[2];          //checking if we're in the right spot
    unsigned strID: 9;
    unsigned strValue : 12;
    unsigned eneID : 9;
    unsigned eneValue : 12;
    unsigned dexID : 9;
    unsigned dexValue : 12;
    unsigned vitID : 9;
    unsigned vitValue : 12;
}

And I'm trying to read to it this way

sFile saveFileStruct;
[...]
saveFile.read((char*)&saveFileStruct, sizeof(saveFileStruct));

I am pretty sure I'm doing something wrong since I get slightly shifted values from what they are supposed to be while the identifier is correct. I would like to know what I am doing wrong here or if there is a better way of doing it.

Thank you.

GreySkull
  • 23
  • 4
  • 1
    You should probably try the reverse: fill your structure with expected values and then write it to a file... check re-reading this file and also compare it to the not-working file. Did you pack the struct? What do you mean with *"slightly shifted values"* please provide 100% exact value examples. – grek40 Apr 17 '17 at 22:47
  • While I try to do the reverse, I'll post the picture of the outcome here. The values that I should receive are stated in the table between parentheses for each of the Values, and the identifiers should be 0,1,2,3. http://i.imgur.com/cFRevtn.png – GreySkull Apr 17 '17 at 22:51
  • Ok, reversing done. I have set the values in the original table and showed the outcome. http://i.imgur.com/f5ywJ1R.png – GreySkull Apr 17 '17 at 23:12
  • Also made another try without any other stuff in there. And it partially works as seen here: http://i.imgur.com/Sn0Ubmp.png – GreySkull Apr 17 '17 at 23:38
  • 1
    Bit field layouts are not standard ; you probably find that the compiler will not make a bitfield span an `unsigned int` unit, e.g. the first 32-bit unit will have the 9,12,9; then the next 12 will start at the start of the next 32-bit unit. To get reliable behaviour, don't use bitfields. – M.M Apr 18 '17 at 00:29
  • 1
    You may want to read the following (http://stackoverflow.com/a/6044223/5265292) and then decide against bitfields for whatever you try to achieve – grek40 Apr 18 '17 at 05:41

0 Answers0