Add *Math.nextPowerOfTwo
See original GitHub issueThere are existing *Math.isPowerOfTwo
methods, it seems like a nextPowerOfTwo
method is a good method to go alongside it, to return the smallest integer >= n
that is a power of two (I was surprised this doesn’t exist in guava already, TBH)
This is a simple operation that has a wide range of applications (sizing buffers, primarily, but it also has uses in collection implementations etc), and it’s not immediately obvious what the bit-twiddling algorithm is doing when it appears in a codebase. Would seem like a prime candidate for an addition to guava.
There’s a simple bit-twiddling algorithm for ints & longs; doubles & bigintegers can probably use a combination of the existing log, floor & pow methods, unless there are clever ways of doing the same for those types (also see http://stackoverflow.com/questions/466204/rounding-up-to-nearest-power-of-2)
Issue Analytics
- State:
- Created 8 years ago
- Reactions:1
- Comments:14 (3 by maintainers)
Top GitHub Comments
@ben-manes thank you. Google (the search engine, not the company) is somehow bad at finding methods in published Guava’s Javadocs.
A simple version of that is below, which is what I use. As its a one-liner I put the method in the class since its only rarely needed.