簡體   English   中英

在Java中讀取hex文件並將其轉換為ascii

[英]Read hex file in java and traduce it into ascii

早上好,我有一個嚴重的問題。 我需要以十六進制讀取文件並將其轉換為ascii。 我還需要在另一個文件上寫ascii。 我是這樣嘗試的:

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws FileNotFoundException, IOException {
    FileInputStream in = new FileInputStream("fileAscii");
    int read;
    String hex = "";
    int count = 0;
    String valueRead="";
    PrintWriter writer= new PrintWriter("fileOutput");

    while ((read = in.read()) != -1) {
        count++;
        valueRead= Integer.toHexString(read);
        if(valueRead.length()==1){
            hex=hex+"0";
        }
        hex = hex + valueRead;
        if (is16Multipler(count)) {

            System.out.println(hex);
            String sb = "";
            StringBuilder temp = new StringBuilder();
            for (int i = 0; i < hex.length() - 1; i += 2) {

                //grab the hex in pairs
                String output = hex.substring(i, (i + 2));
                //convert hex to decimal
                int decimal = Integer.parseInt(output, 16);
                //convert the decimal to character
                sb=sb+(char) decimal;


            }
            if(!sb.equals("00000000000000000000000000000000"))
            {
               writer.println(sb.toString());
            }


               hex = "";
        }
    }
}


public static boolean is16Multipler(int number) {
    if (number % 16 == 0) {
        return true;
    }
    return false;
}

問題是我讀取了錯誤的值,例如讀取83 bat原始文件包含84

此代碼將讀取您的HEx輸入文件並以ASCII字符寫入文件

public static void main(String[] args) throws FileNotFoundException, IOException {
        BufferedReader br = new BufferedReader(new FileReader("fileAscii")); // to read a single line from the file
        int read;
        String src= new String();       // to store the string obtained from buffered reader
        PrintWriter writer= new PrintWriter("fileOutput");
        src=br.readLine();              // read an input line from the file

        while(src!=null){
            src=src.replace(" ", "");   // Trim out the spaces
            for(int i=0;i<src.length();i+=2){
                read=Integer.parseInt(src.substring(i,i+2), 16);    // convert the String to hex integer 
                writer.print((char)read);                           // convert hex to char and write into file
            }
            src=br.readLine();
        }
        writer.flush();
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM