Previous power of 2

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

    Solution with bit manipulation only:

    long FindLargestPowerOf2LowerThanN(long n)
    {
        Assert.IsTrue(n > 0);
    
        byte digits = 0;
        while (n > 0)
        {
            n >>= 1;
            digits++;
        }                            
    
        return 1 << (digits - 1);
    }
    

    Example:

    FindLargestPowerOf2LowerThanN(6):
    Our Goal is to get 4 or 100
    1) 6 is 110
    2) 110 has 3 digits
    3) Since we need to find the largest power of 2 lower than n we subtract 1 from digits
    4) 1 << 2 is equal to 100 
    
    FindLargestPowerOf2LowerThanN(132):
    Our Goal is to get 128 or 10000000
    1) 6 is 10000100
    2) 10000100 has 8 digits
    3) Since we need to find the largest power of 2 lower than n we subtract 1 from digits
    4) 1 << 7 is equal to 10000000 
    

提交回复
热议问题