#### Archived

This topic is now archived and is closed to further replies.

# nearest power of 2

This topic is 5455 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Does anyone know an easy way to calculate the nearest power of 2 of an integer? Thanks!

##### Share on other sites
Whoops, I mean the nearest power of two LARGER than a given integer...

##### Share on other sites
//pseudo-code, largeint is arbitrarylargeint findNextPowerOfTwo(largeint n) {   largeint i = 1;   while(i < n)      i *= 2;   return i;}

cyn

##### Share on other sites
v--;v |= v >> 1;v |= v >> 2;v |= v >> 4;v |= v >> 8;v |= v >> 16;v++;

there you go. if you have v is a power of two then it will just result in the same number. =)

##### Share on other sites
Thank you, I appreciate it!

##### Share on other sites
Assuming an x86 processor is the target:

	_asm	{		bsr ecx, n		mov result, 2		shl result, cl	}

[edited by - Mastaba on October 17, 2003 2:34:29 PM]

##### Share on other sites
For non integers:

ceil(ln(x)/ln(2))

would be the power of 2 greater than x (ie for 7 it would return 3, since 2^3=8). Obviously you could precalc 1/(ln(2)) as 1.4426950408889634073599246810019, then just do:

ceil(ln(x)*1.4426950408889634073599246810019);

This is calculating the base 2 logarithm of x btw, and rounding up, so can be used in other circulstances too.

##### Share on other sites
Transform the number in base 2. Count the number of 1''s and 0''s that you have in the number. This number is the exponent of the smallest power of 2 that is greater than the number given.

1. 1
2. 2
3. 3
Rutin
18
4. 4
5. 5
JoeJ
12

• 14
• 22
• 9
• 31
• 18
• ### Forum Statistics

• Total Topics
632617
• Total Posts
3007475
• ### Who's Online (See full list)

There are no registered users currently online

×