import java.io.*;
public class foo {
public static void main(String[] args) {
try {
DataInputStream input = new DataInputStream(new FileInputStream(
"data.dat"));
while (input.available() > 0) {
String hex = Integer.toHexString(input.readByte()); //I think this is where the problem is
System.out.print(hex + ' ');
}
} catch (IOException e) {
}
}
}
输出-
ffffff89 50 4e 47 d a 1a a 0 0 0 d 49 48 44 52 0 0 0... (continues)
输出大部分是正确的。我无法弄清楚这些 ffffffs 在我的输出中来自哪里。而且单个字符也缺少 0。例如。 d 应显示为 0D
最佳答案
input.readByte()
返回一个有符号字节;当该字节的最高位为 1 时,它被解释为负数,并且 Integer.toString
将其符号扩展为 int。
使用String.format("%02x", input.readByte() & 0xFF)
代替Integer.toString
,它将把字节解释为无符号并且强制使用恰好两个十六进制数字。
关于java - 程序从文件读取字节并转换为十六进制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28909273/