public static void printHexByByteArray2(String fileNames) throws IOException{
FileInputStream in = new FileInputStream(fileNames);
byte[] buf = new byte[64];
int bytes = 0;
int j = 1;
while((bytes = in.read(buf, 0, buf.length)) != -1){
for(int i=0;i<bytes;i++){
if(buf[i] <= 0xf){
System.out.print("0");
}
System.out.print(Integer.toHexString(buf[i] & 0xff)+" ");
if(j++ % 10 == 0){
System.out.println();
}
}
}
in.close();
}
这是错误图片:
Bytes是有符号的整数,数值范围是:-127至+127,而你的条件判断是
if (buf[i] <= 0xf),所有小于F的数,包括负数都会打印0,就出现你的错误了。更改判断条件为:
if ((buf[i] <= 0xf) & (buf[i] >= 0)) ,错误即可纠正
估计你选的文件中含有汉字
if((buf[i]&0xff)<= 0xf){
//单位数前面补0
System.out.print("0");
}
这样也行,用位运算排掉符号位