Question

I seem to be going around in circles with this one... There are many methods to achieve this and I could use a few if statements like I've done int he example below, but I want a smarter method.

Problem

The user is asked to input a value in hex, the program grabs this string and will now want to convert it into an integer, bearing in mind this is a hex value. The input could be for example:

0x00 0xf ff 2

My Attempt

String hexString = response.getResult(); //grabs the user input

int hexInt = Integer.decode(hexString); //Doesn't work if the user doesn't add "0x" at the start

String regex = "\\s*\\b0x\\b\\s*";
String hexInt = hexString.replaceAll(regex, ""); //Doesn't like 0x for some reason

Int hexInt = Integer.valueOf(hexString,16); //Doesn't like 0x

Any ideas on how to do this smartly?

Was it helpful?

Solution

Why not just remove 0x if the string starts with it? There's no need to use a regular expression for this - just a combination of startsWith and substring is simpler to understand (IMO):

String hexString = response.getResult();
if (hexString.startsWith("0x")) {
    hexString = hexString.substring(2);
}
int value = Integer.parseInt(hexString, 16);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top