Page 1 of 1

size of struct with bitfields greater than expected?

Posted: Wed Oct 11, 2023 8:53 am
by nik2000
Hi, I am new to this forum. I am using the Arduino Framework (ESP8266, ESP32). I am basically trying to understand why the total size of the following structure is not 4 bytes like expected. Instead when I print the size out to the serial terminal, it says 6 bytes.

Code: Select all

typedef struct date_time_stamp {
  uint8_t year : 6;
  uint8_t month : 4;
  uint8_t day : 5;
  uint8_t hour : 5;
  uint8_t minute : 6;
  uint8_t second : 6;
  // total size = 32 bits = 4 bytes (expected).
} dtstamp_t;

void setup()
{
    Serial.begin(115200);
    Serial.println();
    Serial.println(sizeof(dtstamp_t));
}

void loop()
{
}

Re: size of struct with bitfields greater than expected?

Posted: Thu Oct 12, 2023 1:53 am
by ESP_Sprite
Probably because you declared the members to be an uint8_t, it tries to pack everything into that type. For instance, the first byte will have 6 bits dedicated to the year. The month is 4 bytes, which doesn't fit in the first uint8_t, so it starts a new one.

Changing the uint8_t to uint32_t will probably fix it.

Re: size of struct with bitfields greater than expected?

Posted: Sat Oct 14, 2023 6:18 pm
by MicroController
You can also let gcc "pack" the bitfields:

Code: Select all

typedef struct __attribute__((packed)) date_time_stamp {
  uint8_t year : 6;
  uint8_t month : 4;
  uint8_t day : 5;
  uint8_t hour : 5;
  uint8_t minute : 6;
  uint8_t second : 6;
  // total size = 32 bits = 4 bytes (expected).
} dtstamp_t;

static_assert(sizeof(dtstamp_t) == 4);