【问题标题】:Read Java in as Hex以十六进制形式读取 Java
【发布时间】:2011-01-16 02:43:53
【问题描述】:

我试图解决这个问题,但我一直想出一些无济于事的东西我相信这很容易(当你当然知道怎么做时;))

我想做的是使用如下字节流读取文件:

while((read = in.read()) != -1){

       //code removed to save space

       Integer.toHexString(read);
System.out.println(read);

}

当它将十六进制打印到屏幕上时,它会打印出很好的数字,例如 31 13 12 0

但是当涉及到应该是 01 31 的十六进制代码时,它将打印 0 131。我想将它读入一个变量,就像您在十六进制编辑器中看到的那样,即 00 11 21 31 没有我需要的单个数字扫描整个文件并寻找我知道该怎么做的模式我只是坚持这个:/

所以简而言之,我需要一个变量来包含两个十六进制字符,即 int temp = 01 而不是 int temp = 0,我希望这一切都有意义,因为现在是凌晨 3 点,我有点困惑!

如果有人知道如何做到这一点,我将不胜感激,p.s 提前感谢您的帮助,这个网站为我节省了大量的研究并学到了很多东西!

非常感谢。

【问题讨论】:

  • 所有要打印的值都适合一个字节?您遇到的问题是 0 到 15(0-F) 之间的数字?

标签: java hex


【解决方案1】:

这个方法:

public static void printHexStream(final InputStream inputStream, final int numberOfColumns) throws IOException{
    long streamPtr=0;
    while (inputStream.available() > 0) { 
        final long col = streamPtr++ % numberOfColumns;
        System.out.printf("%02x ",inputStream.read());
        if (col == (numberOfColumns-1)) {
            System.out.printf("\n");
        }
    }
}

会输出如下内容:

40 32 38 00 5f 57 69 64 65 43 
68 61 72 54 6f 4d 75 6c 74 69 
42 79 74 65 40 33 32 00 5f 5f 
69 6d 70 5f 5f 44 65 6c 65 74 
65 46 69 6c 65 41 40 34 00 5f 
53 65 74 46 69 6c 65 50 6f 69 
6e 74 65 72 40 31 36 00 5f 5f 
69 6d 70 5f 5f 47 65 74 54 65 
6d 70 50 61 74 68 41 40 38 00 

这是你要找的吗?

【讨论】:

    【解决方案2】:

    我认为您正在寻找的是格式化程序。试试:

    Formatter formatter = new Formatter();
    formatter.format("%02x", your_int);
    System.out.println(formatter.toString());
    

    这是否符合您的要求?你的问题不是很清楚(我想你可能从你的 sn-p 中删除了太多代码)。

    【讨论】:

      【解决方案3】:
      import org.apache.commons.io.IOUtils;
      import org.apache.commons.codec.binary.Hex;
      
      InputStream is = new FileInputStream(new File("c:/file.txt"));
      String hexString = Hex.encodeHexString(IOUtils.toByteArray(is));
      

      在 java 7 中,您可以直接从文件中读取字节数组,如下所示:

      import java.nio.file.Files;
      import java.nio.file.Paths;
      import java.nio.file.Path;
      
      Path path = Paths.get("path/to/file");
      byte[] data = Files.readAllBytes(path)     
      

      【讨论】:

        【解决方案4】:

        大家好,大家好,感谢您的回复,但我最终这样做的方式是:

                                hexIn = in.read();
                                s = Integer.toHexString(hexIn);
                                if(s.length() < 2){
                                    s = "0" + Integer.toHexString(hexIn);
                                }
        

        只是想我以后会以我为其他人所做的方式发布它们,不过非常感谢你的帮助!

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-09-13
          • 2016-03-21
          • 2017-07-28
          • 1970-01-01
          • 2015-01-26
          • 2020-10-25
          • 1970-01-01
          相关资源
          最近更新 更多