老師我有個(gè)問題請教一下,我的代碼: 可以直接看加粗字體部分
/** 實(shí)現(xiàn)批量讀取文件 參數(shù)為文件路徑
* @param dir
* @throws IOException
*/
public static void readByBytes(String dir) throws IOException
{
FileInputStream in= new FileInputStream(dir);
byte[] temp=new byte[1024*5];
int count=0;
int j=1;
while((count=(in.read(temp, 0, temp.length)))!=-1)
{
for(int i=0;i<count;i++)
{
if(temp[i]<=0xf)
System.out.print("0");
System.out.print(Integer.toHexString(temp[i]&0xff)+" ");
if(j++%10==0)
System.out.println();
}
}
in.close();
}
問題:加粗那段是判斷如果小于八位,就添加一個(gè)0在前面,可是輸出的結(jié)果有點(diǎn)不太一樣,
例如
0d8 0f6 0a1 7b 03 0f9 0d0 30 5c 094?
24 08e 47 0af 7a 63 36 0e 79 07?
為什么有的輸出是三位,可是最神奇的是,基本上同樣的代碼,只不過在逐個(gè)字節(jié)讀取里,輸出就是正常的。
逐個(gè)字節(jié)讀取代碼如下:?
/**
* 實(shí)現(xiàn)逐個(gè)字節(jié)讀取文件 ?參數(shù)為文件路徑?
* @param dir
* @throws IOException
*/
public static void readByByte(String dir) throws IOException
{
FileInputStream in=new FileInputStream(dir);
int temp=0;
int j=1;
while((temp=in.read())!=-1)
{
if(temp<=0xf)
System.out.print("0");
System.out.print(Integer.toHexString(temp&0xff)+" ");
if(j++%10==0)
System.out.println();
}
in.close();
}
輸出結(jié)果一切正常:
4d 08 73 0c 54 2e bf 29 35 43?
25 81 b2 98 a5 1d 4d 08 4c 4e?
77 53 94 1c d5 0d 12 8e 94 2f?
5a 42 63 24 05 4e 7b 50 ad eb?
40 27 72 5e 94 f5 8b 78 a1 8c?
求解 很納悶
2015-10-27
首先你可以查找相關(guān)的api可以看到,read()方法返回的是0-255之間的一個(gè)數(shù),還有繼續(xù)查閱相關(guān)api可以看到toHexString的時(shí)候,如果你要轉(zhuǎn)化的這個(gè)數(shù)前24位全是0,則不會(huì)把0顯示出來,而這里是0-255之間的數(shù)肯定不會(huì),所以if(temp<=0xf)即可,你說為什么會(huì)有3位(在read(temp, 0, temp.length)方法中),你這樣寫就不會(huì)有了if((temp & 0xff) <= 0xf),具體的可以查閱相關(guān)的api,這里就不過多的解釋了,加油~~~
2014-10-23
從文件讀到的字節(jié)保存到字節(jié)數(shù)組是以byte數(shù)值形式保存的,比如讀取文件中字節(jié)d8,保存到字節(jié)數(shù)組時(shí)d8成為有符號數(shù)值,對應(yīng)的10進(jìn)制是-72,所以在判斷d8(-72)<=0xf(15)是成立的,這樣就出現(xiàn)了0d8的輸出形式??梢栽黾訔l件temp>=0,可以避免出現(xiàn)這樣的情況。
2014-10-08
0xf是十六進(jìn)制的15,用二進(jìn)制表示是1111,不是8位,是4位吧?