Bit hack: Expanding bits

前端 未结 8 1487
名媛妹妹
名媛妹妹 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:03

    Here's a working implementation:

    uint32_t remask(uint16_t x)
    {
        uint32_t i;
        uint32_t result = 0;
        for (i=0;i<16;i++) {
            uint32_t mask = (uint32_t)x & (1U << i);
            result |= mask << (i);
            result |= mask << (i+1);
        }
        return result;
    }
    

    On each iteration of the loop, the bit in question from the uint16_t is masked out and stored.

    That bit is then shifted by its bit position and ORed into the result, then shifted again by its bit position plus 1 and ORed into the result.

提交回复
热议问题