【问题标题】:Inconsistently getting NumberFormatException when trying to convert binary to hex尝试将二进制转换为十六进制时出现不一致的 NumberFormatException
【发布时间】:2018-09-18 13:25:21
【问题描述】:

如果使用变量 bin1,它不会转换,但是如果我用 bin2 替换参数,它似乎可以工作。

我尝试使用 long 而不是 int。还是一样。

public class Test{
    public static void main(String[] args) {
        String bin1 = "11011100000000010001000000000000";
        String bin2 = "01100100001000010001000000000000";

        int dec = Integer.parseInt(bin1, 2);
        String hex = Integer.toString(dec, 16);

        System.out.println(hex);
    }
}

【问题讨论】:

    标签: java binary hex data-conversion number-systems


    【解决方案1】:

    它实际上适用于 longs。

    public class Test{
        public static void main(String[] args) {
            String bin1 = "11011100000000010001000000000000";
            String bin2 = "01100100001000010001000000000000";
    
            long dec = Long.parseLong(bin1, 2);
            String hex = Long.toString(dec, 16);
    
            System.out.println(hex);
        }
    }
    

    结果:

    dc011000
    

    你的号码对于int来说太大了。

    【讨论】:

    • 谢谢。我现在要删除这个帖子吗?我试过了,很长但不是你如何实现的。我错过了那个。
    • @BWB 你不需要删除它。该网站提供的问题和答案可能对未来的其他访问者有用。
    猜你喜欢
    • 2014-05-03
    • 2019-01-10
    • 2012-06-26
    • 2016-08-28
    • 2013-07-25
    相关资源
    最近更新 更多