Bit hack: Expanding bits

前端 未结 8 1485
名媛妹妹
名媛妹妹 2021-02-13 21:27

I am trying to convert a uint16_t input to a uint32_t bit mask. One bit in the input toggles two bits in the output bit mask. Here is an example conver

8条回答
  •  执笔经年
    2021-02-13 22:17

    Try this, where input16 is the uint16_t input mask:

    uint32_t input32 = (uint32_t) input16;
    uint32_t result = 0;
    uint32_t i;
    for(i=0; i<16; i++)
    {
        uint32_t bit_at_i = (input32 & (((uint32_t)1) << i)) >> i;
        result |= ((bit_at_i << (i*2)) | (bit_at_i << ((i*2)+1)));
    }
    // result is now the 32 bit expanded mask
    

提交回复
热议问题