从文件中读取字节并转换为十六进制的程序
Program to read bytes from file and convert to hex
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()
returns 一个带符号的字节;当该字节的最高位为 1 时,它被解释为负数,并且 Integer.toString
将其符号扩展为 int。
使用 String.format("%02x", input.readByte() & 0xFF)
而不是 Integer.toString
,这会将字节解释为无符号并强制使用两个十六进制数字。
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()
returns 一个带符号的字节;当该字节的最高位为 1 时,它被解释为负数,并且 Integer.toString
将其符号扩展为 int。
使用 String.format("%02x", input.readByte() & 0xFF)
而不是 Integer.toString
,这会将字节解释为无符号并强制使用两个十六进制数字。