gpt4 book ai didi

java - 用java读取hex文件并将其转换为ascii

转载 作者:行者123 更新时间:2023-12-01 18:41:48 25 4
gpt4 key购买 nike

早上好,我有一个严重的问题。我需要读取一个十六进制文件并将其转换为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

最佳答案

此代码将读取您的十六进制输入文件并以 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();
}

关于java - 用java读取hex文件并将其转换为ascii,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19679116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com