This is something that's always annoyed me. If you initialize an int with a hex literal, you can use the full range of positive values up to 0xFFFFFF
; anything larger than 0x7FFFFF
will really be a negative value. This is very handy for bit masking and other operations where you only care about the locations of the bits, not their meanings.
But if you use Integer.parseInt() to convert a string to an integer, anything larger than "0x7FFFFFFF"
is treated as an error. There's probably a good reason why they did it that way, but it's still frustrating.
The simplest workaround is to use Long.parseLong() instead, then cast the result to int.
int n = (int)Long.parseLong(s, 16);
Of course, you should only do that if you're sure the number is going to be in the range Integer.MIN_VALUE..Integer.MAX_VALUE
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…