左移循环公式

时间:2013-11-17 13:46:21

标签: c++ c algorithm formula bit-shift

我在程序示例中找到了以下代码:

const unsigned int n = /* something */
unsigned int i = 1;
for (unsigned int j = 1; j < n-1; ++j) {
    i <<= 1;
}

是否有直接公式从i计算n而没有循环?

2 个答案:

答案 0 :(得分:3)

您可以使用:

i = 1 << (n - 2);

或更严格:

#include <limits.h> /* for CHAR_BIT */

const unsigned int n = /* something */;
unsigned int i  = 1;

if( (n - 2) > 0 && (n - 2) < (sizeof(i) * CHAR_BIT) ) {
  i = 1 << (n - 2);
}

答案 1 :(得分:3)

更准确:

  

假设unsigned int是16位(C ++标准规定的最小值)

i = ( n < 18 ) ? ( ( n >= 2 ) ? ( 1 << (n-2) ) : 1 ) : 0;