Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting some hexadecimal string to a decimal integer

I wrote some code to convert my hexadecimal display string to decimal integer. However, when input is something like 100a or 625b (something with a letter) I got an error like this:

java.lang.NumberFormatException: For input string: " 100a" at java.lang.NumberFormatException.forInputString(Unknown Source) at java.lang.Integer.parseInt(Unknown Source)

How can I convert my string with letters to a decimal integer?

if(display.getText() != null)
{
    if(display.getText().contains("a") || display.getText().contains("b") ||
       display.getText().contains("c") || display.getText().contains("d") ||
       display.getText().contains("e") || display.getText().contains("f"))
    {
        temp1 = Integer.parseInt(display.getText(), 16);
        temp1 = (double) temp1;
    }
    else
    {
        temp1 = Double.parseDouble(String.valueOf(display.getText()));
    }
}
like image 965
vontarro Avatar asked Sep 05 '25 11:09

vontarro


2 Answers

It looks like there's an extra (leading) space character in your string (" 100a"). You can use trim() to remove leading and trailing whitespaces:

temp1 = Integer.parseInt(display.getText().trim(), 16);

Or if you think the presence of a space means there's something else wrong, you'll have to look into it yourself, since we don't have the rest of your code.

like image 139
ajb Avatar answered Sep 08 '25 00:09

ajb


public static int hex2decimal(String s) {
    String digits = "0123456789ABCDEF";
    s = s.toUpperCase();
    int val = 0;
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        int d = digits.indexOf(c);
        val = 16*val + d;
    }
    return val;
}

That's the most efficient and elegant solution I have found on the Internet. Some of the other solutions provided here didn't always work for me.

like image 23
AlexAndro Avatar answered Sep 08 '25 01:09

AlexAndro