[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呢?