# Find the closest Power of 2 with JavaScript

One of the things I have been working on over the last couple of days, is a convenient set of functions to manipulate a Processing.js Canvas for use in the CubicVR WebGL Engine. You may already know that a OpenGL performs best with textures with 2^n (power of 2) dimensions. To minimize CPU load, We wanted a way to resize a Processing.js sketch based on it’s distance from the camera.

Why on earth would you want to do this? Well… imagine you have a 3D box spinning around on your screen. The box is far away from the camera and only takes up 16 pixels of the display. On that box you have a texture that is created on the Canvas with Processing.js. The Canvas’s default size is 256px by 256px, but there is absolutely no reason to make the processor calculate a 256×256 pixel animated texture, if the user only ever sees the texture mapped to a 16×16 pixel area.

So the ideal situation is for CubicVR to be able to hook into a Processing.js script and dynamically resize it based on it’s distance from the camera. So one thing we need to be able to do, to create this balance between performance and quality, is to know how to find the closest power of 2.

The following script demonstrates how to find the nearest power of 2 in JavaScript:

```
function nearestPow2( aSize ){
return Math.pow( 2, Math.round( Math.log( aSize ) / Math.log( 2 ) ) );
}

nearestPow2( 127 ); //  128
nearestPow2( 180 ); //  128
nearestPow2( 200 ); //  256
nearestPow2( 256 ); //  256
```

I got the original algorithm from Corban Brook & NotMasterYet on the Processing.js IRC Channel who pointed me to StackOverflow, and I thought it was worth sharing, thanks guys!

We moved off of Disqus for data privacy and consent concerns, and are currently searching for a new commenting tool.

1. I haven’t checked Mathieu’s solution, but I agree that a bitwise calculation is better than calling through to Math functions.

And even if you choose to go the Math route, I’d recommend making local references to reduce scope and object lookups, and bitshift 0 instead of round.

Ex:

var nearestPow2 = (function(Math){
var
pow = Math.pow,
log = Math.log;
return function nearestPow2( aSize ){
return pow( 2, ( log( aSize ) / log( 2 ) ) << 0 );
};
})(Math);

2. This isn’t pretty but here it is with bitwise math (and this doesn’t depend on 32 bit integers either ðŸ˜‰ )

`function nearestPow2(n) {  var m = n;  for(var i = 0; m > 1; i++) {    m = m >>> 1;  }  // Round to nearest power  if (n & 1 << i-1) { i++; }  return 1 << i;}`

Personally I would probably use al’s solution for readability unless the performance of the routine was shown to matter.