why is it?about Integer

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • jackyustb
    New Member
    • Nov 2006
    • 2

    why is it?about Integer

    code as following
    ...
    String s1=Integer.toBi naryString(-1073741824)
    System.out.prin tln(s1);
    int i2=Integer.pars eInt(s1,2);
    ...
    the output is ...
    110000000000000 000000000000000 00
    java.lang.Numbe rFormatExceptio n: For input string: "11000000000000 000000000000000 000"
    at java.lang.Numbe rFormatExceptio n.forInputStrin g(NumberFormatE xception.java:4 8)
    at java.lang.Integ er.parseInt(Int eger.java:480)
    at com.main.Tester .main(Tester.ja va:18)

    what's the matter? how to resolve it?
  • r035198x
    MVP
    • Sep 2006
    • 13225

    #2
    Originally posted by jackyustb
    code as following
    ...
    String s1=Integer.toBi naryString(-1073741824)
    System.out.prin tln(s1);
    int i2=Integer.pars eInt(s1,2);
    ...
    the output is ...
    110000000000000 000000000000000 00
    java.lang.Numbe rFormatExceptio n: For input string: "11000000000000 000000000000000 000"
    at java.lang.Numbe rFormatExceptio n.forInputStrin g(NumberFormatE xception.java:4 8)
    at java.lang.Integ er.parseInt(Int eger.java:480)
    at com.main.Tester .main(Tester.ja va:18)

    what's the matter? how to resolve it?
    110000000000000 000000000000000 00 is not an int (too big)

    The specs say

    "An exception of type NumberFormatExc eption is thrown if any of the following situations occurs:
    • The first argument is null or is a string of length zero.
    • The radix is either smaller than Character.MIN_R ADIX or larger than Character.MAX_R ADIX.
    • Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') provided that the string is longer than length 1.
    • The value represented by the string is not a value of type int. "

    Comment

    • horace1
      Recognized Expert Top Contributor
      • Nov 2006
      • 1510

      #3
      as indicated by r035198x the 32-bit binary value 110000000000000 000000000000000 00
      is too large for an int. If you you convert it to a BigInteger, e.g.
      Code:
      String s1=Integer.toBinaryString(-1073741824);
      System.out.println(s1.length() + " bits " +s1);
      BigInteger bigI = new BigInteger(s1, 2);
      System.out.println("Big integer " + bigI);
      this prints
      32 bits 110000000000000 000000000000000 00
      Big integer 3221225472

      showing that 3221225472 is larger than 2147483647 the maximum value an int can have

      Comment

      • maverick19
        New Member
        • Nov 2006
        • 25

        #4
        the reasons why your int value was long because in binary representation( 2s complement) the first bit is the sign bit.

        Comment

        Working...