size of struct with bitfields greater than expected?

nik2000
Posts: 1
Joined: Wed Oct 11, 2023 8:46 am

size of struct with bitfields greater than expected?

Postby nik2000 » Wed Oct 11, 2023 8:53 am

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()
{
}

ESP_Sprite
Posts: 9724
Joined: Thu Nov 26, 2015 4:08 am

Re: size of struct with bitfields greater than expected?

Postby ESP_Sprite » Thu Oct 12, 2023 1:53 am

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.

MicroController
Posts: 1701
Joined: Mon Oct 17, 2022 7:38 pm
Location: Europe, Germany

Re: size of struct with bitfields greater than expected?

Postby MicroController » Sat Oct 14, 2023 6:18 pm

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);

Who is online

Users browsing this forum: No registered users and 46 guests