/**************************************************************************
* Author: Isai Damier
* Title: Reverse Bits of Byte (8-bit)
* Project: geekviewpoint
* Package: algorithms
*
* Statement:
* Given an integer, reverse its bit sequence.
*
* Sample Input: 00100110
* Sample Output: 01100100
*
* 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 (8-bit)
* inputs.
**************************************************************************/
public byte reverseBitsByte(byte x) {
int intSize = 8;
byte 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 reverseBitsByte method, of class Bitwise.
*/
@Test
public void testReverseBitsByte() {
System.out.println(""reverseBitsByte"");
String a = ""00100110"";
String b = ""01100100"";
byte x = Byte.parseByte(a,2);
byte r = Byte.parseByte(b,2);
Bitwise bits = new Bitwise();
assertEquals(r, bits.reverseBitsByte(x));
assertEquals(x, bits.reverseBitsByte(r));
}
}