字节数组与16进制字符串互转

时间:2022-01-09 10:46:06
    private static final int zero = java.lang.Math.abs(Byte.MIN_VALUE);
    private static final byte[][] hexList = new byte[zero+Byte.MAX_VALUE+1][];
    static{
        for(int i=0; i<Byte.MAX_VALUE*2+2; i++){
            byte b = (byte) (Byte.MIN_VALUE+i);
            int num = (int)b;
            if (num < 0) {
                num = num + 256;
            }
            String sTemp = Integer.toHexString(num).toUpperCase();
            if (sTemp.length() == 1) {
                sTemp = "0" + sTemp;
            }
            hexList[b+zero] = sTemp.getBytes();
        }
    }


    /**
     * 将字节数组转化为一个16进制的字符串
     *
     * @param b 原始字节数组
     *
     * @return 16进制的字符串
     */
    public static String getHexString(byte[] b) {
        byte[] bytes = new byte[b.length*2];
        for (int i = 0; i < b.length; i++) {
            int offset = b[i]+zero;
            bytes[i*2] = hexList[offset][0];
            bytes[i*2+1] = hexList[offset][1];
        }
        return new String(bytes);
    }


    public static byte[] hex2Bytes(String s) throws IOException {
        int i = s.length() / 2;
        byte result[] = new byte[i];
        int j = 0;
        if (s.length() % 2 != 0){
            throw new IOException("hexadecimal string with odd number of characters");
}
for (int k = 0; k < i; k++) { char c = s.charAt(j++); int l = "0123456789abcdef0123456789ABCDEF".indexOf(c); if (l == -1){ throw new IOException("hexadecimal string contains non hex character");
}
int i1 = (l & 0xf) << 4; c = s.charAt(j++); l = "0123456789abcdef0123456789ABCDEF".indexOf(c); i1 += l & 0xf; result[k] = (byte) i1; } return result; }