Android 16进制和byte[]互转

  • Post author:
  • Post category:其他


public class Hex {

    /**
     * @param hex 16进制字符串
     * @return 字节数组
     */
    public static byte[] toBytes(String hex) {
        if (hex.contains(" ")) {
            hex = hex.replace(" ", "");
        }
        hex = hex.toUpperCase();
        int len = hex.length() / 2;
        char[] hexChars = hex.toCharArray();
        byte[] bytes = new byte[len];
        for (int i = 0; i < len; i++) {
            int pos = i * 2;
            bytes[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return bytes;
    }

    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    /**
     * @param bytes 字节数组
     * @return 16进制字符串(空格隔开)
     */
    public static String toString(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        int len = bytes.length;
        for (int i = 0; i < len; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xff);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
            //空格格式显示每个字节
            if (i != len - 1) {
                hexString.append(" ");
            }
        }
        return hexString.toString().toUpperCase();
    }


}



版权声明:本文为u012127961原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。