Bit hack: Expanding bits

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

    A simple loop. Maybe not bit-hacky enough?

    uint32_t thndrwrks_expand(uint16_t x) {
      uint32_t mask = 3;
      uint32_t y = 0;
      while (x) {
        if (x&1) y |= mask;
        x >>= 1;
        mask <<= 2;
      }
      return y;
    }
    

    Tried another that is twice as fast. Still 655/272 as slow as expand_bits(). Appears to be fastest 16 loop iteration solution.

    uint32_t thndrwrks_expand(uint16_t x) {
      uint32_t y = 0;
      for (uint16_t mask = 0x8000; mask; mask >>= 1) {
        y <<= 1;
        y |= x&mask;
      }
      y *= 3;
      return y;
    }
    

提交回复
热议问题