java: convert binary string to int

后端 未结 3 653
我在风中等你
我在风中等你 2020-12-20 16:12

I\'m trying to convert a couple of binary strings back to int. However it doesn\'t convert all my binary strings, leaving me a java.lang.NumberFormatException

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-20 16:59

    As explained above, Integer.toBinaryString() converts ~0 and ~1 to unsigned int so they will exceed Integer.MAX_VALUE.

    You could use long to parse and convert back to int as below.

    int base = 2;
    for (Integer num : new Integer[] {~0, ~1}) {
        String binaryString = Integer.toBinaryString(num);            
        Long decimal = Long.parseLong(binaryString, base);
        System.out.println("INPUT=" + binaryString + " decimal=" + decimal.intValue()) ;
    }
    

提交回复
热议问题