作者a0tim (~TIM~)
看板java
標題[問題] 請問關於HEX檔的讀檔
時間Sun Apr 28 14:07:26 2013
小弟我最近在學8051微處理機
寫好的程式經過編譯成.hex檔後還要轉成.bin檔
但是課本附的.hex檔轉.bin檔的程式在WIN7-x64無法執行
於是想用java自己寫個轉檔程式
爬文後聽說.hex檔最好用
FileInputStream來讀檔
然而轉換過程如下
public class HEX2BIN {
public static void main(String[] args){
File F1 = new File("C:\\000.hex");
File F2 = new File("C:\\123.bin");
String F1_S = "";
String S = "";
try {
F2.createNewFile();
BufferedReader BR = new BufferedReader(new InputStreamReader(new
FileInputStream(F1)));
while((S=BR.readLine()) != null){
S = S.substring(1);
//.hex檔每行第一個字都是':'
F1_S += hexToBin(S);
}
BufferedWriter BW = new BufferedWriter(new FileWriter(F2));
BW.write(F1_S);
BW.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
}
}
public static String hexToBin(String hex){
String bin = "";
String binFragment = "";
int iHex;
hex = hex.trim();
hex = hex.replaceFirst("0x", "");
for(int i = 0; i < hex.length(); i++){
iHex = Integer.parseInt(""+hex.charAt(i),16);
binFragment = Integer.toBinaryString(iHex);
while(binFragment.length() < 4){
binFragment = "0" + binFragment;
}
bin += binFragment;
}
return bin;
}
}
轉換出來的.bin檔並不能如預期的執行
不知是否哪裡出問題了
懇請大大解答一下,謝謝!
附上.hex檔:
http://ppt.cc/wcb_
附上.bin檔:
http://ppt.cc/0g1Z
PS.以上是課本附的程式轉換的結果,不是我轉的
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 123.192.152.111
※ 編輯: a0tim 來自: 123.192.152.111 (04/28 14:14)
※ 編輯: a0tim 來自: 123.192.152.111 (04/28 14:18)
→ tkcn:我不懂你為什麼附自己的程式碼 + 課本程式的轉換結果....? 04/28 14:35
→ tkcn:btw,課本程式轉換可能是換行字元\r\n 的問題,拿掉 \r 試試 04/28 14:44
推 PsMonkey:檔案格式問題基本上跟實作語言無關,故暫時鎖文 04/28 16:20
→ Marquess:你附上的hex跟bin檔在資料內容上不一致 05/01 11:33
推 sbrhsieh:看到Reader/Writer,不必看其他,九成九是錯的 05/01 16:33