返回比输入值大的第一个2的整数次幂

  在研究GoAhead源码时,看到一个函数定义如下:

ContractedBlock.gif ExpandedBlockStart.gif View Code
 
   
1 /* **************************************************************************** */
2   /*
3 * Find the smallest binary memory size that "size" will fit into. This
4 * makes the ringq and ringqGrow routines much more efficient. The balloc
5 * routine likes powers of 2 minus 1.
6 */
7
8 static int getBinBlockSize( int size)
9 {
10 int q;
11
12 size = size >> B_SHIFT;
13 for (q = 0 ; size; size >>= 1 ) {
14 q ++ ;
15 }
16 return ( 1 << (B_SHIFT + q));
17 }
18
19   /* **************************************************************************** */

     它的功能:如果参数size<2的 B_SHIFT次方(定义在uemf.h中,为4),则返回2的B_SHIFT次方。如果参数size>=2的B_SHIFT次方,则返回大于2的B_SHIFT次方的第一个2的整数次幂。

  把这个问题简化一下:要求写一个函数,该函数返回比输入参数大的第一个2的整数次幂。代码如下:

ContractedBlock.gif ExpandedBlockStart.gif View Code
 
   
1 #include < iostream.h >
2
3 int getBinBlockSize( int size);
4 void main()
5 {
6 int a;
7 cout << " please input a positive integer: " ;
8 cin >> a;
9 cout << getBinBlockSize(a) << endl;
10 }
11
12 int getBinBlockSize( int size)
13 {
14 for ( int q = 0 ;size > 0 ;size >>= 1 )
15 {
16 q ++ ;
17 }
18
19 return 1 << q;
20 }

  在VC中测试通过,该函数的核心思想有两点:1.统计输入参数所占用的2进制位,用到右移操作。2.计算2的N次幂,左移操作高效。这个函数理解了,那么上面的函数就好理解了,只是加了一个比较阈值B_SHIFT而已。

转载于:https://www.cnblogs.com/strider/articles/2052325.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值