Friday, 14 August 2015

Isolate right most set bit

‘x = x & (-x)’ isolate right most set bit.

100            000001100100
-100            111110011100
-------------------------------
100 & -100 000000000100
-------------------------------

public class IsloateNthBit {

 public static int isolateRightMostNthBit(int num) {
  num = num & (-num);
  return num;
 }
}


Following is the junit test case.

import static org.junit.Assert.assertEquals;

import org.junit.Test;

public class IsloateNthBitTest {

 @Test
 public void test1(){
  assertEquals(IsloateNthBit.isolateRightMostNthBit(100), 4);
  assertEquals(IsloateNthBit.isolateRightMostNthBit(123), 1);
  assertEquals(IsloateNthBit.isolateRightMostNthBit(204), 4);
  assertEquals(IsloateNthBit.isolateRightMostNthBit(256), 256);
 }
}



No comments:

Post a Comment