JDK-7006142 : Error parsing String representing signed binary number (2-complement)
  • Type: Bug
  • Component: core-libs
  • Sub-Component: java.lang
  • Affected Version: 6u22
  • Priority: P4
  • Status: Closed
  • Resolution: Duplicate
  • OS: windows_7
  • CPU: x86
  • Submitted: 2010-12-10
  • Updated: 2014-04-03
  • Resolved: 2012-03-28
Related Reports
Duplicate :  
Duplicate :  
Description
FULL PRODUCT VERSION :
JDK 1.6_18

ADDITIONAL OS VERSION INFORMATION :
Windows 7

A DESCRIPTION OF THE PROBLEM :
int i=Integer.parseInt(Integer.toBinaryString(-1), 2);
ought to return -1, but


Exception in thread "main" java.lang.NumberFormatException: For input string: "11111111111111111111111111111111" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:48)
	at java.lang.Integer.parseInt(Integer.java:461)

STEPS TO FOLLOW TO REPRODUCE THE PROBLEM :
Problem occurs every time you try to parse a string with the sign-bit set

Byte.parseByte("11111111",2) fails because it calls Integer.ParseInt and therafter chechs the value againt -128 and -127


REPRODUCIBILITY :
This bug can be reproduced always.

---------- BEGIN SOURCE ----------
	public static void main(String[] args) {
		int num=-1;
		String binString=Integer.toBinaryString(num);
		System.out.println(binString);
		//result: 11111111111111111111111111111111 (32 bits)
		// now try to reverse
		num=Integer.parseInt(binString, 2);
		//and we crashes
		// java.lang.NumberFormatException:
		//For input string: "11111111111111111111111111111111"
	}
---------- END SOURCE ----------

CUSTOMER SUBMITTED WORKAROUND :
		if (binString.charAt(0)=='1')
			binString=binString.substring(1);
		num=Integer.parseInt(binString, 2)-Integer.MIN_VALUE;

Comments
EVALUATION The output of Integer.toBinaryString is unsigned; read it back in using Integer.parseUnsignedInt. Closing as duplicate of 4215269.
28-03-2012