Previous power of 2

后端 未结 11 1443
一整个雨季
一整个雨季 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:34

    When you work in base 2, you can jump from a power of two to the next one by just adding or removing a digit from the right.

    For instance, the previous power of two of the number 8 is the number 4. In binary:

    01000 -> 0100 (we remove the trailing zero to get number 4)

    So the algorithm to solve the calculus of the previous power of two is:

    previousPower := number shr 1

    previousPower = number >> 1

    (or any other syntax)

提交回复
热议问题