Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Bits {
- /**
- * readBit
- * Determine if n bit is set.
- * bit is 0 based
- * @param value: the integer to read the bit from
- * @param bit: the bit to read, 0 based
- * @return true if bit is set; false if not set
- */
- public static boolean readBit(int value, int bit) {
- // raising 2 to the power of the needed bit set that bit in posVal
- int posVal = (int)Math.pow(2, (double)bit);
- // the result of the bitwise AND (&) will equal posVal
- // only if the bit is set in value
- if ((value & posVal) == posVal) {
- return true;
- } else {
- return false;
- }
- } // end readBit()
- /**
- * Set n bit in the integer value.
- * bit is 0 based.
- * @param value
- * @param bit
- * @return value with the n bit set
- */
- public static int setBit(int value, int bit) {
- // raising 2 to the power of the needed bit set that bit in posVal
- int posVal = (int)Math.pow(2, (double)bit);
- // using bitwise OR (|) will make sure that bit is set value
- return value | posVal;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement