输入16进制数序列,将其二进制反序并输出新的16进制数
输入16进制数序列,如
输入:1a1bf
二进制:0001 1010 0001 1011 1111
反转:1111 1101 1000 0101 1000
输出:FD858
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| import java.io.BufferedReader; import java.io.InputStreamReader;
public class BitReverse {
* @param args */ public static void main(String[] args) { BufferedReader bReader = new BufferedReader(new InputStreamReader(System.in)); try { String string = bReader.readLine(); bReader.close(); byte[] bt = getByte(string); 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) { 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()); } }
|