Thursday 13 August 2015

Check whether nth bit is set or not


public class ChecknthBitSet {

 public static boolean isNthBitSet(int num, int position) {
  while (position > 0) {
   num = num >> 1;
   position--;
  }

  return ((num & 1) == 1);
 }
}


import static org.junit.Assert.*;

import org.junit.Test;

public class ChecknthBitSetTest {
 @Test
 public void test1(){
  assertTrue(ChecknthBitSet.isNthBitSet(165, 0));
  assertTrue(ChecknthBitSet.isNthBitSet(165, 2));
  assertTrue(ChecknthBitSet.isNthBitSet(165, 5));
  assertTrue(ChecknthBitSet.isNthBitSet(165, 7));
  
  assertFalse(ChecknthBitSet.isNthBitSet(165, 1));
  assertFalse(ChecknthBitSet.isNthBitSet(165, 3));
  assertFalse(ChecknthBitSet.isNthBitSet(165, 4));
  assertFalse(ChecknthBitSet.isNthBitSet(165, 6));
  assertFalse(ChecknthBitSet.isNthBitSet(165, 8));
  assertFalse(ChecknthBitSet.isNthBitSet(165, 9));
  assertFalse(ChecknthBitSet.isNthBitSet(165, 10));
  
 }
}

No comments:

Post a Comment