Previous power of 2

后端 未结 11 1463
一整个雨季
一整个雨季 2020-11-30 05:42

There is a lot of information on how to find the next power of 2 of a given value (see refs) but I cannot find any to get the previous power of two.

The only way I f

11条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 06:47

    From Hacker's Delight, a nice branchless solution:

    uint32_t flp2 (uint32_t x)
    {
        x = x | (x >> 1);
        x = x | (x >> 2);
        x = x | (x >> 4);
        x = x | (x >> 8);
        x = x | (x >> 16);
        return x - (x >> 1);
    }
    

    This typically takes 12 instructions. You can do it in fewer if your CPU has a "count leading zeroes" instruction.

提交回复
热议问题