I'm an embedded software (firmware) developer (C++) and sometimes I need to convert data between types, for example
In order to do the conversion properly, I am using a union, to store the data, so I can read/write it in both ways, for example
union {
uint8_t asByte[lengthInBytes]{}; // interprete the data as 16 bytes
uint32_t asUint32[lengthInWords]; // interprete the data as 4 32bit words
} state;
Now I am running static code checking on my code (using SonarCloud) and this is flagging an issue on this construct :
Add a discriminant to this wrapped undiscriminated union or replace it with an "std::variant"
I don't want to use the std:: library containers because I need to avoid using dynamic memory allocation, and often it's also an overkill...
So how can I resolve this 'codeSmell', or should I just ignore/accept it in my use case ?
Thanks for all the useful remarks,
Seems like std::bitcast
is the right way to do this.
It requires C++20 but I think I'm ok with that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With