Search code examples
c++bit-manipulation

How do you obtain the upper 15 bits of a uint16_t?


I have the following 2 bytes to decode: 0000 0000 0111 1011

and I wish to fill this structure

struct ctn
{
    uint16_t fx : 1;
    uint16_t stn: 15;

    ctn() : fx(0), stn(0) {}
} PACKED;

I store the 2 bytes of data to decode in a uint16_t tmp1;

I think to get the fx value (the 1 at the end of the binary string) like this:

composedTrackNumber.fx = tmp1 & 1;

How do I extract the remaining 15 bits into the stn variable?

composedTrackNumber.stn = ???

Solution

  • You should shift the value to the right by 1:

    composedTrackNumber.stn = (tmp1 >> 1) & 0x7FFF;
    

    Do & 0x7FFF to make sure correct value is set for stn.

    There is also another way, you can avoid bitfields and use getter functions to get the respective field values.

    struct ctn
    {
        uint16_t value = 0;
    
        uint16_t get_stn() const { return (value >> 1) & 0x7FFF; }
        uint16_t get_fx() const { return value & 0x1; }
    };
    
    int main()
    {
        uint16_t tmp1 = 32768;
        ctn composedTrackNumber{tmp1};
        std::cout << composedTrackNumber.get_fx() << ' ' << composedTrackNumber.get_stn() << '\n';
    }