Converting 32-bit binary string with Integer.parseInt fails

前端 未结 4 720
慢半拍i
慢半拍i 2020-12-07 01:14

Why does this part of code fail:

Integer.parseInt(\"11000000000000000000000000000000\",2);

Exception in thread \"main\" java.lang.NumberFormatException: For         


        
4条回答
  •  囚心锁ツ
    2020-12-07 02:08

    Even though your string, "11.....lots of zeros" is a legal binary representation of a negative integer, Integer.parseInt() fails on it. I consider this a bug.

    Adding a little levity, since on rereading this post it sounds too pedantic, I understand that Oracle probably doesn't care much whether I think this is a bug or not. :-)

    You can try:

       long avoidOverflows = Long.parseLong("11000000000000000000000000000000",2);
       int thisShouldBeANegativeNumber = (int)avoidOverflows);
       System.out.println(avoidOverflows + " -> " + thisShouldBeANegativeNumber);
    

    you should see
    3221225472 -> -1073741824

    You sometimes have to do this with Colors depending on how they are stored as text.

    BTW, exact thing can happen if you are parsing a Hex representation and you are parsing a negative number like "88888888". You need to use Long.parseLong() then convert.

提交回复
热议问题