【问题标题】:Display 0 value in hex file在 hex 文件中显示 0 值
【发布时间】:2012-12-24 17:21:16
【问题描述】:

我正在处理一个十六进制文件并显示其内容,但如果值是“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”?

【问题讨论】:

    标签: java hex


    【解决方案1】:

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

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

    System.out.print(String.format("%02x ", readHexFile));
    

    【讨论】:

      【解决方案2】:

      在屏幕上显示时,“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");
      }
      

      【讨论】:

        【解决方案3】:

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

        Scanner sc = new Scanner(new File(fileName));
        while(sc.hasNext()) {
            String s = sc.next();
            System.out.println(s);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2014-01-24
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-09-28
          • 1970-01-01
          相关资源
          最近更新 更多