美文网首页
Java Hex字符串与byte数组互转

Java Hex字符串与byte数组互转

作者: DemonLms | 来源:发表于2019-11-26 10:04 被阅读0次
import java.util.Arrays;

/**
 * Created by Demon on 2019/11/6
 */
public abstract class Converts {
    private final static char[] digits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
    private final static byte[] undigits = new byte[128];

    static {
        char[] lower = "0123456789abcdef".toCharArray();
        char[] upper = "0123456789ABCDEF".toCharArray();
        Arrays.fill(undigits, (byte) -1);
        for (byte i = 0; i < 16; i++) {
            undigits[lower[i]] = i;
        }
        for (byte i = 0; i < 16; i++) {
            undigits[upper[i]] = i;
        }
    }

    public static String bytesToHex(byte[] bytes) {
        char[] chars = new char[bytes.length << 1];
        for (int i = 0; i < bytes.length; i++) {
            chars[i << 1] = digits[(bytes[i] >> 4) & 0xF];
            chars[(i << 1) + 1] = digits[bytes[i] & 0xF];
        }
        return new String(chars);
    }

    public static byte[] hexToBytes(String hex) {
        byte[] bytes = new byte[hex.length() >> 1];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) (undigits[hex.charAt(i << 1)] << 4 | undigits[hex.charAt((i << 1) + 1)]);
        }
        return bytes;
    }
}

相关文章

网友评论

      本文标题:Java Hex字符串与byte数组互转

      本文链接:https://www.haomeiwen.com/subject/qcqewctx.html