Created
August 5, 2011 08:48
-
-
Save mbykovskyy/1127146 to your computer and use it in GitHub Desktop.
Handy methods for working with power of two values.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public int nextPowerOfTwo(int value) { | |
return 1 << 32 - Integer.numberOfLeadingZeros(value - 1); | |
} | |
public int previousPowerOfTwo(int value) { | |
return 1 << 31 - Integer.numberOfLeadingZeros(value); | |
} | |
public boolean isPowerOfTwo(int value) { | |
return (value & -value) == value; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment