Reverse Bits of Short (16-bit)
by Isai Damier

/**************************************************************************
 * Author: Isai Damier
 * Title: Reverse Bits of Short (16-bit)
 * Project: geekviewpoint
 * Package: algorithms
 *
 * Statement:
 *   Given an integer, reverse its bit sequence.
 *
 * Sample Input:  0000000100100110
 * Sample Output: 0110010010000000
 *
 * Technical Details:
 *   It is necessary to know whether the decimal number being passed as
 *   input is of type byte (8-bit) or short (16-bit) or int (32-bit) or
 *   long (64-bit): because Java will discard leading zeroes. For instance,
 *   if x = 0011010, Java will trim it to 11010 and then cause the reverse
 *   to look like 1011. Under such circumstances the reverseBits operation
 *   would not be reversible.
 *
 *   To keep things simple, the presented algorithm treats short (16-bit)
 *   inputs.
 **************************************************************************/ 
 public short reverseBitsShort(short x) {
  int intSize = 16;
  short y=0;
  for(int position=intSize-1; position>0; position--){
    y+=((x&1)<<position);
    x >>= 1;
  }
  return y;
}
import org.junit.Test;
import static org.junit.Assert.*;

public class BitwiseTest {

 /**
   * Test of reverseBitsShort method, of class Bitwise.
   */
  @Test
  public void testReverseBitsShort() {
    System.out.println(""reverseBits"");
    String a = ""0000000100100110"";
    String b = ""0110010010000000"";
    short x = Short.parseShort(a,2);
    short r = Short.parseShort(b,2);
    Bitwise bits = new Bitwise();
    assertEquals(r, bits.reverseBitsShort(x));
    assertEquals(x, bits.reverseBitsShort(r));
  }
}