c++bit-manipulationbit-shiftsign-extension

Signed extension from 24 bit to 32 bit in C++


I have 3 unsigned bytes that are coming over the wire separately.

[byte1, byte2, byte3]

I need to convert these to a signed 32-bit value but I am not quite sure how to handle the sign of the negative values.

I thought of copying the bytes to the upper 3 bytes in the int32 and then shifting everything to the right but I read this may have unexpected behavior.

Is there an easier way to handle this?

The representation is using two's complement.


Solution

  • You could use:

    uint32_t sign_extend_24_32(uint32_t x) {
        const int bits = 24;
        uint32_t m = 1u << (bits - 1);
        return (x ^ m) - m;
    }
    

    This works because:

    Templated version

    template<class T>
    T sign_extend(T x, const int bits) {
        T m = 1;
        m <<= bits - 1;
        return (x ^ m) - m;
    }