From 178c7b9d40e06a04790542241912ca21d2c7b92f Mon Sep 17 00:00:00 2001
From: Sven Gothel
+ * We rely on the JVM spec {@link Integer#SIZE} == 32.
+ *
@@ -67,6 +75,9 @@ public interface Bitfield {
* http://tekpool.wordpress.com/category/bit-count/
* http://www.hackersdelight.org/
*
+ *
+ * We rely on the JVM spec {@link Integer#SIZE} == 32.
+ *
+ * Source: bithacks: http://www.graphics.stanford.edu/~seander/bithacks.html#DetermineIfPowerOf2
+ *
+ * We rely on the JVM spec {@link Integer#SIZE} == 32. + *
+ */ + public static final int nextPowerOf2(int n) { + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + return (n < 0) ? 1 : n + 1; // avoid edge case where n is 0, it would return 0, which isn't a power of 2 + } + /** + * If the given {@code n} is not {@link #isPowerOf2(int)} return {@link #nextPowerOf2(int)}, + * otherwise return {@code n} unchanged. + *+ * return isPowerOf2(n) ? n : nextPowerOf2(n); + *+ *
+ * We rely on the JVM spec {@link Integer#SIZE} == 32. + *
+ */ + public static final int roundToPowerOf2(final int n) { + return isPowerOf2(n) ? n : nextPowerOf2(n); + } } /** * Simple {@link Bitfield} factory for returning the efficient implementation. -- cgit v1.2.3