鹰之歌

既然你崇拜鹰,就要像鹰一样翱翔天际,俯瞰大地。哪怕会摔的粉身碎骨。

导航

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

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

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的整数次幂。代码如下:

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而已。

posted on 2011-05-20 20:41  鹰之歌  阅读(339)  评论(0编辑  收藏  举报