Union containing struct -> union constructor gets auto-deleted

Status
Not open for further replies.

Ben

Well-known member
Hi,

I'm using a Struct for some calibration data, this way I can easily save and load the data from EEPROM using EEPROM.get and EEPROM.put. This works great, now I'd like to add a CRC checksum using Frank's FastCRC library. FastCRC expects the data as a char array, so I created a union containing the struct and a char array of the same size. This does not compile as the union's constructor seems to get implicitly deleted. Here's a minimal example to reproduce the problem:

Code:
struct S1 {
  uint32_t  foo = 0x00;
  uint32_t  crc = 0x00;
};
union U1 {
  S1        s;
  uint8_t   c[8];
};

U1 u;

void setup() {}
void loop() {}

My intention was to then use the FastCRC function somewhat like so:
Code:
CRC32.crc32(u.c, sizeof(u.s - 4))

If there is a better or more elegant way to use FastCRC on a struct I'd happily abandon the whole struct-in-union contraption :rolleyes:...

Cheers
Ben
 
Hi,

I think I solved this myself :)
Code:
#include <FastCRC.h>

struct S1 {
  uint32_t  foo = 0x1234CDEF;
  float     bar = 1.0f;
};
FastCRC32 CRC32;
void setup() {
  delay(2000);
  S1 s;
  Serial.println(myCRC32(s),HEX);
}
void loop() {}

uint32_t myCRC32(S1 s) {
  uint8_t b[sizeof(s)];
  for(size_t i=0; i < sizeof(s); i++) {
    b[i] = *( (uint8_t *) &s + i);
    Serial.print("Byte ");
    Serial.print(i);
    Serial.print("\tcontains\t0x");
    Serial.println(b[i], HEX);
}
  uint32_t checksum = CRC32.crc32(b, sizeof(b));
  return checksum;
}

Output:
Byte 0 contains 0xEF
Byte 1 contains 0xCD
Byte 2 contains 0x34
Byte 3 contains 0x12
Byte 4 contains 0x0
Byte 5 contains 0x0
Byte 6 contains 0x80
Byte 7 contains 0x3F
9A3622C0
 
Status
Not open for further replies.
Back
Top