符号付き整数として格納するのに 33 ビットが必要な数値を解析しようとするため、コードは失敗します。
A signed int
is a 32 bit value in two's complement representation, where the first bit will indicate the sign of the number, and the remaining 31 bits the value of the number. (-ish.) Java only supports signed integers, and parseInt()
and friends aren't supposed to parse two's complement bit patterns – and thus interpret the 1
or (possibly implied) 0
at the 32nd position from the right as the sign. They're meant to support parsing a human-readable reprentation, which is an optional -
(or +
) for the sign, followed by the absolute value of a number.
このコンテキストでは、説明した動作を期待するのは誤った直感です。基数 2 以外の基数 (または、他の一般的に使用される 2 のべき乗基数) を解析している場合、次の最初の桁を期待しますか?サインに影響を与える入力?明らかにそうではないでしょう。たとえば、意図的にparseInt("2147483648")
リターン-2147483648
することは、PHP レベルの狂気です。
特殊ケースの 2 のべき乗ベースも奇妙に感じます。この回答のように、ビットパターンを処理するための別のアプローチを用意することをお勧めします。