Search code examples
javaparsingprimitiveshort

Error parsing 16 bit short


short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive)

Why does the following

System.out.println(Short.parseShort("1111111111111111", 2));

Return

java.lang.NumberFormatException: Value out of range.

An exception of type NumberFormatException 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_RADIX or larger than Character.MAX_RADIX.

  • Any character of the string is not a digit of the specified radix, except that the first character may be a minus sign '-' ('\u002D') or plus sign '+' ('\u002B') provided that the string is longer than length 1.

  • The value represented by the string is not a value of type short.

I assume the error is from the last bullet, but I thought 16 '1' bits is equivalent to -1 when using Short. Thus, it should be valid?


Solution

  • The javadoc that you quoted states that Short.parseShort parses numbers as signed numbers.

    1111111111111111 (16 1 digits) when read as a signed number means 216 - 1 or 65535. That is too large to be represented as a short.

    Alternatives:

    • If there was an alternative to parseShort that parsed unsigned values, that would work. (But there isn't ...)

    • You could use Integer.parseInt, do a range check on the int result, and then cast it to a short.


    I thought 16 '1' bits is equivalent to -1 when using Short. Thus, it should be valid?

    Unfortunately, no. The parseInt method parses signed values.

    Thought experiment: what if the user entered 1111111111111111 with the intention that it really meant a positive signed number; i.e. +65535? How would that mesh with your idea that the parse method treats signed and unsigned as interchangeable?