'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()));
    }
}


Solution 1:[1]

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.

Solution 2:[2]

My way:

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

Solution 3:[3]

//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();
        }
    }
}

Solution 4:[4]

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.

Solution 5:[5]

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;
 }

Solution 6:[6]

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';
}

Solution 7:[7]

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

Solution 8:[8]

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);
}

Solution 9:[9]

    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);

Solution 10:[10]

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);

Solution 11:[11]

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");

    }
}

Solution 12:[12]

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

BigInteger("625b", 16)