I have a string which I want to convert to Integer, I know that this can be achieved using Integer.parseInt(number)
Or by using Integer.parseInt(number, base)
for a particular base.
I can use above function with a if else condition to check the base of number represented by string.
Example:
int intValue;
if(string.startsWith("0x"))
intValue = Integer.parseInt(string.substring(2), 16)
//handle other cases
else
intValue - Integer.parseInt(string) //base 10
I was wondering if there is there any inbuilt function that does this job of converting string representing number in any base to corresponding integer?
Integer.decode(String nm)
is designed exactly for your needs. From docs:
The sequence of characters following an optional sign and/or radix specifier ("0x", "0X", "#", or leading zero) is parsed as by the Integer.parseInt method with the indicated radix (10, 16, or 8).
Here is fragment of Integer
source code responsible for radix distinction:
if (nm.startsWith("0x", index) || nm.startsWith("0X", index)) {
index += 2;
radix = 16;
} else if (nm.startsWith("#", index)) {
index ++;
radix = 16;
} else if (nm.startsWith("0", index) && nm.length() > 1 + index) {
index ++;
radix = 8;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.