Note for beginners: I use hexadecimal (0-9 and A-F) because one hexadecimal digit maps to 4 binary bits perfectly. Instead of writing 1010, I use A (10 decimal). You can tell Java to use hexadecimal (literals) by starting with 0x as in 0x0A.
As stated before, 1 should output 8 (0001 to 1000). So instead of while(x!=0), the code needs to shift the first bit as far as the length of the bits needed in this example it is 4.
for (int i = 0; i < 4; ++i) { // not while (x!=0){ b<<=1; b|=( x &1); x>>=1; } Hex convert 0-F: 0=0 1=8 2=4 3=C 4=2 5=A 6=6 7=E 8=1 9=9 A=5 B=D C=3 D=B E=7 F=F
Or full 8 bit example:
public static byte reverse(byte x) { byte b = 0; for (int i = 0; i < 8; ++i) { b<<=1; b|=( x &1); x>>=1; } return b; } public static void main(String args[]) { byte[] nums = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, (byte) 0xAA, (byte) 0xFE, (byte) 0xFF }; for (byte b : nums) { System.out.printf("%02X=%02X ", b, reverse(b)); } System.out.println(); }
Output:
00=00 01=80 02=40 03=C0 04=20 05=A0 06=60 07=E0 08=10 09=90 0A=50 0B=D0 0C=30 0D=B0 0E=70 0F=F0 10=08 11=88 AA=55 FE=7F FF=FF
Integer.reverse(int i)- but as it looks like you want to reverse integers with less bits, I leave it as a comment.