This is what always annoyed me. If you initialize an int with a hexadecimal literal, you can use the entire range of positive values โโup to 0xFFFFFF ; nothing more than 0x7FFFFF will really be a negative value. This is very convenient for masking bits and other operations in which you only care about the locations of the bits and not about their values.
But if you use Integer.parseInt () to convert a string to an integer, anything greater than "0x7FFFFFFF" is treated as an error. There is probably a good reason they did it, but itโs still frustrating.
The simplest workaround is to use Long.parseLong () instead, and then convert the result to int.
int n = (int)Long.parseLong(s, 16);
Of course, you should only do this if you are sure that the number will be in the range Integer.MIN_VALUE..Integer.MAX_VALUE
Alan Moore May 10 '09 at 2:05 p.m. 2009-05-10 14:05
source share