79422109

Date: 2025-02-07 20:34:08
Score: 2
Natty:
Report link

The data must be aligned correctly to avoid potential issues with undefined behaviour.

That is not true, generally. You should be able to write safe programs, without undefined behaviour, without dealing at all with alignment. If you have any specific case against this idea, or any specific compiler/architecture that does not hold to this, please post it.

On some platforms (for example x86) rather than undefined behaviour, there is a performance penalty.

Yes, some datatypes are faster to be loaded into registers if they are properly aligned

I understand that in many cases, the required alignment is the same width as the datatype

Yes, and the reason is the same than above. If that helps, you can imagine that somehow, registers are also "aligned", and so moving several bytes to some register is faster if the alignments match.

I want to write some data serialization and deserialization code to read and write data into a buffer. This data will be sent via a network socket between multiple machines. In this case, it would be reasonable to assume that the machines will all have the same endianness to avoid the overhead of needing to discuss converting between host and network byte order.

There are entire books dedicated to binary serialization formats, and yes, alignment, endianness, and precission are key factors to them. My actual answer, if you are in fact presented with the challenge to send data over the network, is to stick with any already established cross-language binary protocol.

Examples:

  1. protobuf https://protobuf.dev/
  2. thrift https://thrift.apache.org/
  3. Binary JSON https://bsonspec.org/
Reasons:
  • RegEx Blacklisted phrase (2.5): please post
  • RegEx Blacklisted phrase (1): I want
  • Long answer (-1):
  • No code block (0.5):
  • High reputation (-1):
Posted by: robermorales