Java 打印byte数组的16进制字符串

每个byte为8位,用16进制表示需要2个16进制位
比如:
半个byte:(二进制1111) == (十进制15) == (十六进制f)
一个byte:(二进制11111111) == (十进制255) == (十六进制ff)

import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class Test {
    public static void main(String[] args) {
        MessageDigest messageDigest = null;
        try {
            String str = "测试字符串";
            messageDigest = MessageDigest.getInstance("SHA1");
            messageDigest.update(str.getBytes("UTF-8"));
            byte bytes[] = messageDigest.digest();

            BigInteger bigInteger = new BigInteger(1, bytes);
            System.out.println(bigInteger.toString(16));


            String strHexBytes = DatatypeConverter.printHexBinary(bytes);
            System.out.println(strHexBytes);


            System.out.println(bytes2hex(bytes));
        } catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static String bytes2hex(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        String tmp = null;
        for (byte b : bytes) {
            // 将每个字节与0xFF进行与运算,然后转化为10进制,然后借助于Integer再转化为16进制
            tmp = Integer.toHexString(0xFF & b);
            if (tmp.length() == 1) {     
                tmp = "0" + tmp;
            }
            sb.append(tmp);
        }
        return sb.toString();

    }
}

你可能感兴趣的:(Java 打印byte数组的16进制字符串)