Java实现hex和bytes之间相互转换

版权声明:本文为博主原创文章,未经博主允许不得转载。深圳夸克时代在线技术有限公司 官网:http://www.kksdapp.com https://blog.csdn.net/wahaha13168/article/details/82903898
public static byte[] hexToBytes(String hex) {
    hex = hex.length() % 2 != 0 ? "0" + hex : hex;

    byte[] b = new byte[hex.length() / 2];
    for (int i = 0; i < b.length; i++) {
        int index = i * 2;
        int v = Integer.parseInt(hex.substring(index, index + 2), 16);
        b[i] = (byte) v;
    }
    return b;
}

public static String bytesToHex(byte[] bytes) {
    char[] hexChars = new char[bytes.length * 2];

    for (int j = 0; j < bytes.length; j++) {
        int v = bytes[j] & 0xFF;
        hexChars[j * 2] = hexArray[v >>> 4];
        hexChars[j * 2 + 1] = hexArray[v & 0x0F];
    }
    return new String(hexChars);
}

猜你喜欢

转载自blog.csdn.net/wahaha13168/article/details/82903898