Test Bit
by Isai Damier, Android Engineer @ Google

/***************************************************************************
 * Author: Isai Damier
 * Title: Test Bit
 * Project: geekviewpoint
 * Package: algorithms
 *
 * Statement:
 *   Given a bit sequence, indicate whether the kth bit is set.
 *   The zeroth (0th) bit is the least significant
 *    (rightmost) bit.
 *
 * Sample Input:  0010010010, 4
 * Sample Output: true
 * 
 * Technical Details: Let x = 0010010010. Then only the 1st, 4th,
 *    and the 7th bits are set. Therefore, testBit(x,4) would return
 *    TRUE while testBit(x,2) would return FALSE.
 *
 *     testBit is a three steps operation:
 *     step_1] Using the shift-left operator << create a bit
 *         sequence where only the kth bit is set.
 *     step_2] Take the bitwise AND of x and the sequence in step_1.
 *         This operation will force clear all the bits in x; except
 *         the kth bit. It leaves the kth bit unchanged.
 *     step_3] Compare the result of step_2 to zero (0). This step
 *          is effectively comparing the kth bit to zero.
 *
 **************************************************************************/ 
 public boolean testBit(int x, int kth) {
  return (x & 1 << kth) != 0;
}
import org.junit.Test;
import static org.junit.Assert.*;

public class BitwiseTest {

 /**
   * Test of testBit method, of class Bitwise.
   */
  @Test
  public void testTestBit() {
    System.out.println(""testBit"");
    String s = ""0010010010"";
    int len = s.length() - 1;
    int x = Integer.parseInt(s, 2);
    Bitwise bits = new Bitwise();
    for (int i = len; i >= 0; i--) {
      if (s.charAt(i) == '1') {
        assertTrue(bits.testBit(x, len - i));
      } else {
        assertFalse(bits.testBit(x, len - i));
      }
    }
  }
}