什么是最快的算法来返回2的幂的数的功率? [英] What is the fastest algorithm to return the power of a number which is a power of 2?
本文介绍了什么是最快的算法来返回2的幂的数的功率?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定n = 2 ^ k,我如何找到k假设n是32位整数使用C / C ++位方式?
Given n = 2^k, how can I find k assuming n is 32-bit integer using C/C++ bitwise?
推荐答案
您可以使用二进制指数显式存储在浮点数的事实:
Well, you could use the fact that the binary exponent is explicitly stored in floating point numbers:
unsigned log2(unsigned x)
{
float f = x;
memcpy(&x, &f, sizeof x);
return (x >> 23) - 127;
}
我不知道这有多快,而且肯定不是
I don't know how fast this is, and it surely is not the most portable solution, but I find it quite interesting.
只是为了好玩,这里是一个完全不同的,相对直接的解决方案:
And just for fun, here is a completely different, relatively straightforward solution:
unsigned log2(unsigned x)
{
unsigned exp = 0;
for (; ;)
{
switch (x)
{
case 128: ++exp;
case 64: ++exp;
case 32: ++exp;
case 16: ++exp;
case 8: ++exp;
case 4: ++exp;
case 2: ++exp;
case 1: return exp;
case 0: throw "illegal input detected";
}
x >>= 8;
exp += 8;
}
}
这里是一个完全展开的解决方案:
And here is a completely unrolled solution:
#define CASE(exp) case (1 << (exp)) : return (exp);
unsigned log2(unsigned x)
{
switch (x)
{
CASE(31) CASE(30) CASE(29) CASE(28)
CASE(27) CASE(26) CASE(25) CASE(24)
CASE(23) CASE(22) CASE(21) CASE(20)
CASE(19) CASE(18) CASE(17) CASE(16)
CASE(15) CASE(14) CASE(13) CASE(12)
CASE(11) CASE(10) CASE( 9) CASE( 8)
CASE( 7) CASE( 6) CASE( 5) CASE( 4)
CASE( 3) CASE( 2) CASE( 1) CASE( 0)
default: throw "illegal input";
}
}
这篇关于什么是最快的算法来返回2的幂的数的功率?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文