十六进制到二进制

时间:2018-02-12 03:53:04

标签: java binary hex filereader

我正在阅读十六进制数字并将其转换为二进制数字。它工作正常,直到我读到fffffff8'十六进制,通过异常。

这是我不断获得的例外:

Exception in thread "main" java.lang.NumberFormatException: For input string: "fffffff8"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)
    at hexToDecimal.hex2decimal.main(hex2decimal.java:33)

这是我的代码:

public static void main(String[] args) {
    String line;
    String toBinary;
    try {
        // myFile
        URL url = hex2decimal.class.getResource("gcc.trace");
        File file = new File(url.getPath());
        FileReader fileReader = new FileReader(file);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        StringBuffer stringBuffer = new StringBuffer();

        while ((line = bufferedReader.readLine()) != null) {
            if (line.length() == 15){
               //line example: s 0x1fffff50 1

                line = line.substring(4, line.length() -3);
            }
            else if (line.length() == 14){
            line = line.substring(4, line.length() -2);
            }

            toBinary = Integer.toBinaryString(Integer.parseInt(line, 16));
            while (toBinary.length() < 32 ){
                toBinary = "0" +toBinary;
            }
            System.out.println(toBinary);
            stringBuffer.append(line);
            stringBuffer.append("\n");
        }
        fileReader.close();
        System.out.println("Contents of file:");
        System.out.println(stringBuffer.toString());
    } catch (IOException e) {
        e.printStackTrace();
    }


}

1 个答案:

答案 0 :(得分:1)

Integer的最大值是

 public static final int   MAX_VALUE = 0x7fffffff

当您尝试解析超过最大NumberFormatException的数字时, 0xfffffff8(4294967288)&gt; 0x7fffffff(2147483647)

尝试Long.parseLong(line, 16),其最大值为0x7fffffffffffffffL