I found the following code in a program example:
const unsigned int n = /* something */
unsigned int i = 1;
for (unsigned int j = 1; j < n-1; ++j) {
i <<= 1;
}
Is there a direct formula to compute i
from n
without a loop ?
I found the following code in a program example:
const unsigned int n = /* something */
unsigned int i = 1;
for (unsigned int j = 1; j < n-1; ++j) {
i <<= 1;
}
Is there a direct formula to compute i
from n
without a loop ?
You can use:
i = 1 << (n - 2);
or more strict:
#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);
}
More accurately:
assuming unsigned int is 16 bits (minimum as specified by C++ standard)
i = ( n < 18 ) ? ( ( n >= 2 ) ? ( 1 << (n-2) ) : 1 ) : 0;