2

我正在处理一个十六进制文件并显示其内容,但如果该值为“0”。我打印出来的时候没有出现。

例如

 0 0 0 b7 7a 7a e5 db 40 2 0 c0 0 0 9 18 16 0 e3 1 40 0 0 3f 20 f0 1 5 0 0 0 0 0 0 41 bc 7a e5 db 40 2 0 c0 1 0 9 18 16 0 e3 1 40 0 0 3f 20 f0 1 5 0 0 0 0 0 0 53 3f 7b e5 db 40 2 0 c0 3 0 9 2 19 24 3d 0 22 68 1 db 9

代码

    String filename = "C:\\tm09888.123";
    FileInputStream in = null;
    int readHexFile = 0; 
    char hexToChar = ' ';
    String[] bytes = new String[10];

    try
    {            
        in = new FileInputStream(filename); 

        while((readHexFile = in.read()) != -1)
        {       
            if (Integer.toHexString(readHexFile).equals("f0"))
            {
                System.out.print("\n\n\n");
            }
            System.out.print(Integer.toHexString(readHexFile) + " ");
        }
    }
    catch (IOException ex)
    {
        Logger.getLogger(NARSSTest.class.getName()).log(Level.SEVERE, null, ex);
    }  

}  

当我打印出文件时,“0”没有出现,“c0”等值变成了“c”。

我如何重写代码以显示“0”?

4

3 回答 3

4

Integer.toHexString不保证返回两位数的结果。

如果您希望它始终为两位数,则可以String.format改用:

System.out.print(String.format("%02x ", readHexFile));
于 2012-12-24T17:29:04.027 回答
1

当它显示在屏幕上时,“0”值没有出现,像“c0”这样的值变成只有“c”

我怀疑“0c”更有可能变成“c”。我希望“c0”没问题。

问题是您正在使用Integer.toHexString它只会使用所需数量的数字。您可以通过编写手动解决此问题:

if (readHexFile < 0x10) {
    System.out.print("0");
}

或者,只需使用:

private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray();
...
System.out.print(HEX_DIGITS[readHexFile >> 4]);
System.out.print(HEX_DIGITS[readHexFile % 15]);
System.out.print(" ");

或者更简单:

System.out.printf("%02x ", readHexFile);

另请注意,无需转换为十六进制字符串即可与0xf0. 您可以使用:

if (readHexFile == 0xf0) {
    System.out.print("\n\n\n");
}
于 2012-12-24T17:26:40.630 回答
0

我不能说代码有什么问题,但如果你使用扫描仪,事情似乎会更清楚

Scanner sc = new Scanner(new File(fileName));
while(sc.hasNext()) {
    String s = sc.next();
    System.out.println(s);
}
于 2012-12-24T17:33:51.260 回答