Search code examples
c++structarduino-esp8266

uint32_t in struct not working as expected


I am trying to read the header of a bitmap file, using structs, but the uint32_t members do not contain the expected value.

The start of the file contains this data: 424d 36e6 0100 0000

Minimal Example:

#include <SPI.h>
#include <SD.h>

File myFile;

struct s1 {
  uint16_t v16;
  uint32_t v32;
};
s1 structvar;

struct s2 {
  uint16_t v16_1;
  uint16_t v16_2;
  uint16_t v16_3;
};
s2 structvar2;

uint16_t v16;
uint32_t v32;

void setup() {
  Serial.begin(9600);

  Serial.print("Initializing SD card...");

  if (!SD.begin(4)) {
    Serial.println("initialization failed!");
    return;
  }
  Serial.println("initialization done.");

  myFile = SD.open("IMAGE001.BMP", FILE_READ);
  if (myFile) {
    Serial.println("Struct1");
    myFile.read(&structvar,6);
    Serial.println(structvar.v16);
    Serial.println(structvar.v32);

    myFile.seek(0);
    Serial.println("Struct2");
    myFile.read(&structvar2,6);
    Serial.println(structvar2.v16_1);
    Serial.println(structvar2.v16_2);
    Serial.println(structvar2.v16_3);

    myFile.seek(0);
    Serial.println("Separate vars");
    myFile.read(&v16,2);
    myFile.read(&v32,4);
    Serial.println(v16);
    Serial.println(v32);   

    myFile.close(); 
  }
}

void loop() {
  // nothing happens after setup finishes.
  delay(100);
}

Output:

Struct1
19778    //0x4d42
1        //0x00000001 - Lower half only
4        //4 Bytes - correct size.

Struct2
19778    //0x4d42
58934    //0xe636 - Upper Half
1        //0x0001 - Lower Half

Separate vars
19778    //0x4d42
124470   //0x0001e636 - Correct

So, it looks like the uint_32_t members of the structs only contain the lower half of the (little-endian) data, whereas if I read the uint_32_t as 2xuint16_t, or if I read the uint16_t & uint32_t values separately, then they contain the correct data

What am I missing? Is this something to do with packing?


Solution

  • Most likely you are having alignment optimization affecting your code. You should use something like this

    #pragma pack(push, 1) // one byte alignment
    struct s1 {
      uint16_t v16;
      uint32_t v32;
    };
    struct s2 {
      uint16_t v16_1;
      uint16_t v16_2;
      uint16_t v16_3;
    };
    #pragma pack(pop)
    

    also you can improve reads like in the below to not manually do everything

    myFile.read(&structvar2, sizeof(structvar2));