Advertisement
eeperry

Java Class to Read and Write Bits to Integers

May 16th, 2014
320
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.12 KB | None | 0 0
  1. public class Bits {
  2.    
  3.     /**
  4.      * readBit
  5.      * Determine if n bit is set.
  6.      * bit is 0 based
  7.      * @param value: the integer to read the bit from
  8.      * @param bit: the bit to read, 0 based
  9.      * @return true if bit is set; false if not set
  10.      */
  11.     public static boolean readBit(int value, int bit) {
  12.         // raising 2 to the power of the needed bit set that bit in posVal
  13.         int posVal = (int)Math.pow(2, (double)bit);
  14.         // the result of the bitwise AND (&) will equal posVal
  15.         // only if the bit is set in value
  16.         if ((value & posVal) == posVal) {
  17.             return true;
  18.         } else {
  19.             return false;
  20.         }
  21.     } // end readBit()
  22.    
  23.     /**
  24.      * Set n bit in the integer value.
  25.      * bit is 0 based.
  26.      * @param value
  27.      * @param bit
  28.      * @return value with the n bit set
  29.      */
  30.     public static int setBit(int value, int bit) {
  31.         // raising 2 to the power of the needed bit set that bit in posVal
  32.         int posVal = (int)Math.pow(2, (double)bit);
  33.         // using bitwise OR (|) will make sure that bit is set value
  34.         return value | posVal;
  35.     }
  36.    
  37. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement