MD5序列后的值转为32位16进制数

本文详细介绍了三种将Java字节数组转换为十六进制字符串的方法,包括基本实现、效率对比及应用场景。适用于Java开发中需要进行字节与十六进制互转的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法一:

 private static String bytesToHexString(byte[] bytes) {
	        // http://stackoverflow.com/questions/332079
	        StringBuilder sb = new StringBuilder();
	        for (int i = 0; i < bytes.length; i++) {
	            String hex = Integer.toHexString(0xFF & bytes[i]);
	            if (hex.length() == 1) {
	                sb.append('0');
	            }
	            sb.append(hex);
	        }
	        return sb.toString();
	    }


 方法二

public static String toHexString(byte[] bytes) {
    char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    char[] hexChars = new char[bytes.length * 2];
    int v;
    for ( int j = 0; j < bytes.length; j++ ) {
        v = bytes[j] & 0xFF;
        hexChars[j*2] = hexArray[v/16];
        hexChars[j*2 + 1] = hexArray[v%16];
    }
    return new String(hexChars);
}


http://stackoverflow.com/questions/332079/in-java-how-do-i-convert-a-byte-array-to-a-string-of-hex-digits-while-keeping-l

 

方法三:

public static String getMD5(String path){
		try {
			MessageDigest digest = MessageDigest.getInstance("MD5");
			return getHashString(digest.digest(path.getBytes()));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} 
		return null;
	}

	private static String getHashString(byte[] digest) {
		StringBuilder builder = new StringBuilder();
		for(byte b : digest){
			builder.append(Integer.toHexString((b >> 4) & 0xf));
			builder.append(Integer.toHexString( b & 0xf));
		}
		return builder.toString();
	}



 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值