输入16进制数序列,如
输入:1a1bf
二进制:0001 1010 0001 1011 1111
反转:1111 1101 1000 0101 1000
输出:FD858
import java.io.BufferedReader; import java.io.InputStreamReader; public class BitReverse { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); try { String string = bReader.readLine(); bReader.close(); byte[] bt = getByte(string); //System.out.println("bt"+bt.length); byte[] res = new byte[bt.length]; for(int i=0; i<res.length; ++i){ res[i] = reverse(bt[res.length-i-1]); } print(res); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 将读入的16进制序列字符串,转换为byte数组 * @param str * @return * @throws Exception */ private static byte[] getByte(String str) throws Exception{ byte[] bt = new byte[(int)Math.round(str.length()/2.0)]; str = str.toLowerCase(); int k = 0, j = 0; for(int i=0; i<str.length(); i=i+2){ k = 0; j = 0; k = getInt(str.charAt(i)); if((i+1)<str.length()) j = getInt(str.charAt(i+1)); bt[(i/2)] = (byte)((k<<4) | j); } return bt; } /** * 将一个表示16进制的字符,转为相应的数字,用int存储,a-10,b-11,5-5 * @param temp * @return * @throws Exception */ private static int getInt(char temp) throws Exception{ if(temp >= '0' && temp <= '9') return (temp-'0'); else if (temp >= 'a' && temp <= 'f') { return (temp-'a'+10); }else { throw new Exception("非十六进制数"); } } /** * 对byte b的二进制进行反转,使用Integer的reverse函数。也可自己进行位操作 * @param b * @return */ private static byte reverse(byte b){ Integer temp = (int)b; temp = Integer.reverse(temp); return (byte)(temp>>24); } private static void print(byte[] b){ String string = ""; for(int i=0; i<b.length; ++i){ string += Integer.toHexString(b[i] & 0xff); } System.out.println(string.toUpperCase()); } }