Safely converting a non-owning pointer of multiple uint8_t's to uint16_t's

67 Views Asked by At

I am getting data from a serial wire, thus the received data is an array of bytes (uint8_t). but these bytes are essentially a lot of two byte words (uint16_t). I am wondering what the best practice is to safely viewing a single pair of bytes or multiple pairs as uint16_t's without copying the data. The received data is in the format [Word_1_LSB, Word_1_MSB, ..., Word_N_LSB, Word_N_MSB] to account for the little endian architecture of where my code needs to run.

The received data is stored in a static uint8_t buffer and then std::span is used to hand out parts of the buffer as needed.

To avoid always memcpy-ing the data around, which would require additional buffers, or performing manual bit calculations, as discussed in this questions, is it somehow be possible to go from std::span<uint8_t, size> to std::span<uint16_t, size/2> or are there alignment problems? This would also be desirable for span's with dynamic extent.

Another idea was to use reinterpret_cast, as the data is laid out correctly for the endianness.

Finally I considered using a union to "reinterpret" the values with the below union, but I don't see how to convert multiple values at once this way.

union TwoBytes {
    uint8_t bytes[2];
    uint16_t combined;
};

What is the best practice to do so, using up to C++20?

0

There are 0 best solutions below