Help with bytes management in C++

if you control the hardware you know about the endianness so can make an "hardwired" coding decision.

As you'll also be using GCC on both side (likely) I would suggest to force packing the bits together and fixed size types.

struct __attribute__((packed)) t_payload {
  uint8_t  id;
  uint16_t rawData;
};

t_payload payload;
1 Like

The bit operators do not care, it's when overlaying types that endianness comes into play. My 5 cents: If the data ever has to be interpreted by different devices, then determine which byte order to use and use bitwise operators. It's portable and not that difficult with some practice.

Hmm, not sure how that got through. Should be an OR or a +. I have edited the original post in case someone stops reading there.

I suspect you'll be better served using bitwise-or for slicing and merging.

Thank you, this keyword is totally new to me. I am really happy I asked for the advice.

Thank you, semantically this is 100% exactly what I would like to do.
But, as stated subsequently by others, the concern would be whether the compiler is going to do what I expect it is going to do...

I wonder if there is any mileage in organizing the structure as a C++ Class instead of a struct? Does that provide any additional fidelity guarantee?

A class and a struct are virtually identical.
The only difference is that in a struct access is public by default, but in a class it is private.