28

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()));
    }
}
2
  • Don't forget that hex is case insensitive, so you should check for capital A-F as well. Commented Nov 21, 2013 at 1:18
  • 5
    It is dangerous to conclude that only numbers with hex digits "a" thru "f" are hexadecimal. It is quite possible for a hexadecimal value to not contain any of these digits at all. Commented Nov 21, 2013 at 1:37

13 Answers 13

62

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Good catch! Never would have seen that.
17
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.

3 Comments

Doesn't work for me. I tried to passing it the String number 0a470c00025f424a. Even I tried to return long instead of int
In the for loop, just loop through each char in s.toCharArray(). I checked, it's quicker.
@PeterMortensen Impossible to remember at this moment, have passed 7 years :) I suppose for some inputs did not get always the expected output.
4
//package com.javatutorialhq.tutorial;

import java.util.Scanner;

/* Java code to convert hexadecimal to decimal */
public class HexToDecimal {

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        System.out.print("Hexadecimal Input: ");

        // Read the hexadecimal input from the console

        Scanner s = new Scanner(System.in);

        String inputHex = s.nextLine();

        try {
            // Actual conversion of hexadecimal to decimal

            Integer outputDecimal = Integer.parseInt(inputHex, 16);

            System.out.println("Decimal Equivalent: " + outputDecimal);
        }

        catch(NumberFormatException ne) {

            // Printing a warning message if the input
            // is not a valid hexadecimal number

            System.out.println("Invalid Input");
        }

        finally {
            s.close();
        }
    }
}

Comments

3

My way:

private static int hexToDec(String hex) {
    return Integer.parseInt(hex, 16);
}

Comments

1

A much simpler way is to use BigInteger, like so:

BigInteger("625b", 16)

Comments

0

This is my solution:

public static int hex2decimal(String s) {
    int val = 0;
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        int num = (int) c;
        val = 256*val + num;
    }
    return val;
}

For example to convert 3E8 to 1000:

StringBuffer sb = new StringBuffer();
sb.append((char) 0x03);
sb.append((char) 0xE8);
int n = hex2decimal(sb.toString());
System.out.println(n); //will print 1000.

Comments

0

You can use this method to get the digit:

public int digitToValue(char c) {
   (c >= '&' && c <= '9') return c - '0';
   else if (c >= 'A' && c <= 'F') return 10 + c - 'A';
   else if (c >= 'a' && c <= 'f') return 10 + c - 'a';
   return -1;
 }

Comments

0

Since there is no brute-force approach which (done with it manualy). To know what exactly happened.

Given a hexadecimal number

KₙKₙ₋₁Kₙ₋₂....K₂K₁K₀

The equivalent decimal value is:

Kₙ * 16ₙ + Kₙ₋₁ * 16ₙ₋₁ + Kₙ₋₂ * 16ₙ₋₂ + .... + K₂ * 16₂ + K₁ * 16₁ + K₀ * 16₀

For example, the hex number AB8C is:

10 * 16₃ + 11 * 16₂ + 8 * 16₁ + 12 * 16₀ = 43916

Implementation:

 //convert hex to decimal number
private static int hexToDecimal(String hex) {
    int decimalValue = 0;
    for (int i = 0; i < hex.length(); i++) {
        char hexChar = hex.charAt(i);
        decimalValue = decimalValue * 16 + hexCharToDecimal(hexChar);
    }
    return decimalValue;
}
private static int hexCharToDecimal(char character) {
    if (character >= 'A' && character <= 'F')
        return 10 + character - 'A';
    else //character is '0', '1',....,'9'
        return character - '0';
}

Comments

0

You could take advantage of ASCII value for each letter and take off 55, easy and fast:

int asciiOffset = 55;
char hex = Character.toUpperCase('A');  // Only A-F uppercase
int val = hex - asciiOffset;
System.out.println("hexadecimal:" + hex);
System.out.println("decimal:" + val);

Output:
hexadecimal:A
decimal:10

1 Comment

Please provide some explanation
-1
void htod(String hexadecimal)
{
    int h = hexadecimal.length() - 1;
    int d = 0;
    int n = 0;

    for(int i = 0; i<hexadecimal.length(); i++)
    {
        char ch = hexadecimal.charAt(i);
        boolean flag = false;
        switch(ch)
        {
            case '1': n = 1; break;
            case '2': n = 2; break;
            case '3': n = 3; break;
            case '4': n = 4; break;
            case '5': n = 5; break;
            case '6': n = 6; break;
            case '7': n = 7; break;
            case '8': n = 8; break;
            case '9': n = 9; break;
            case 'A': n = 10; break;
            case 'B': n = 11; break;
            case 'C': n = 12; break;
            case 'D': n = 13; break;
            case 'E': n = 14; break;
            case 'F': n = 15; break;
            default : flag = true;
        }
        if(flag)
        {
            System.out.println("Wrong Entry"); 
            break;
        }
        d = (int)(n*(Math.pow(16,h))) + (int)d;
        h--;
    }
    System.out.println("The decimal form of hexadecimal number "+hexadecimal+" is " + d);
}

Comments

-1
    Scanner sc = new Scanner(System.in);
    System.out.println("Enter the value");
    String s = sc.next();
    //String s = "AD";
    String s1 = s.toUpperCase();
    int power = 0;
    double result = 0;      
    char[] c = s1.toCharArray();
    for (int i = c.length-1; i >=0  ; i--) {
        boolean a = true;
        switch(c[i]){
        case 'A': c[i] = 10; a = false; break;
        case 'B': c[i] = 11; a = false; break;
        case 'C': c[i] = 12; a = false; break;
        case 'D': c[i] = 13; a = false; break;
        case 'E': c[i] = 14; a = false; break;
        case 'F': c[i] = 15; a = false; break;  
        }
        if(a==true){
            result = result + (c[i]-48) * Math.pow(16, power++);
       }else {
           result = result + (c[i]) * Math.pow(16, power++);
       }

    }
    System.out.println(result);

1 Comment

I simplify the solution.
-1

This is a little library that should help you with hexadecimals in Java: https://github.com/PatrykSitko/HEX4J

It can convert from and to hexadecimals. It supports:

  • byte
  • boolean
  • char
  • char[]
  • String
  • short
  • int
  • long
  • float
  • double (signed and unsigned)

With it, you can convert your String to hexadecimal and the hexadecimal to a float/double.

Example:

String hexValue = HEX4J.Hexadecimal.from.String("Hello World");
double doubleValue = HEX4J.Hexadecimal.to.Double(hexValue);

Comments

-1

Use:

public class Hex2Decimal {

    public static void hexDec(String num)
    {
        int sum = 0;
        int newnum = 0;
        String digit = num.toUpperCase();
        for(int i=0; i<digit.length(); i++)
        {
            char c = digit.charAt(digit.length()-i-1);

            if(c == 'A')
            {
                newnum = 10;
            }
            else if(c == 'B')
            {
                newnum = 11;
            }
            if(c == 'C')
            {
                newnum = 12;
            }
            if(c == 'D')
            {
                newnum = 13;
            }
            if(c == 'E')
            {
                newnum = 14;
            }
            if(c == 'F')
            {
                newnum = 15;
            }
            else
            {
                newnum = Character.getNumericValue(c);
            }
            sum = (int) (sum + newnum*Math.pow(16, i));
        }

        System.out.println(" HexaDecimal to Decimal conversion is" + sum);
    }

    public static void main(String[] args) {

        hexDec("9F");

    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.