lifeneedyou 2009-06-09 15:20
浏览 244
已采纳

请教一段代码的解释:java 算文件的MD5值是怎么用十六进制表示的?

[code="java"]
import java.io.*;
import java.security.*;

public class HashFile {

/**
 * @param args
 */
public static char[] hexChar = { '0', '1', '2', '3', '4', '5', '6', '7',
        '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

public static void main(String[] args) {
    String fileName = "F:\\soft\\Firefox.exe";
    String hashType = "MD5";
    try {
        System.out.println(hashType + " == " + getHash(fileName, hashType));

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public static String getHash(String fileName, String hashType)
        throws Exception {
    InputStream fis;
    fis = new FileInputStream(fileName);
    byte[] buffer = new byte[1024];
    MessageDigest md5 = MessageDigest.getInstance(hashType);
    int numRead = 0;
    while ((numRead = fis.read(buffer)) > 0) {
        md5.update(buffer, 0, numRead);
    }
    fis.close();
    return toHexString(md5.digest());
}

public static String toHexString(byte[] b) {
    StringBuilder sb = new StringBuilder(b.length * 2);
    for (int i = 0; i < b.length; i++) {
        sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
        sb.append(hexChar[b[i] & 0x0f]);
    }
    return sb.toString();
}

}[/code]
请高手解释以下toHexString(byte[] b)方法,主要是这两句:
[code="java"]sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
sb.append(hexChar[b[i] & 0x0f]);[/code]
hexChar[(b[i] & 0xf0>>> 4,hexChar[b[i] & 0x0f]这到底是什么意识?
谢谢!
[b]问题补充:[/b]
谢谢楼上的!大致明白了,这里应该是拿字节byte和十六进制的做and的比较!但这里为什么要用0xf0呢?

  • 写回答

3条回答 默认 最新

  • wanghaolovezlq 2009-06-09 15:28
    关注

    &这个是位运算“且”

    sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
    //(b[i] & 0xf0)这个意思就是取b[i]的后4位
    “>>> 无符号右移”

    sb.append(hexChar[b[i] & 0x0f]);
    //这个意思就是取b[i]的前4位

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥88 找成都本地经验丰富懂小程序开发的技术大咖
  • ¥15 如何处理复杂数据表格的除法运算
  • ¥15 如何用stc8h1k08的片子做485数据透传的功能?(关键词-串口)
  • ¥15 有兄弟姐妹会用word插图功能制作类似citespace的图片吗?
  • ¥200 uniapp长期运行卡死问题解决
  • ¥15 请教:如何用postman调用本地虚拟机区块链接上的合约?
  • ¥15 为什么使用javacv转封装rtsp为rtmp时出现如下问题:[h264 @ 000000004faf7500]no frame?
  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集