26

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()));
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vontarro
  • 339
  • 1
  • 3
  • 14
  • Don't forget that hex is case insensitive, so you should check for capital A-F as well. – stevevls Nov 21 '13 at 01: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. – scottb Nov 21 '13 at 01:37

13 Answers13

58

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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ajb
  • 31,309
  • 3
  • 58
  • 84
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.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
AlexAndro
  • 1,918
  • 2
  • 27
  • 53
  • 1
    Doesn't work for me. I tried to passing it the String number `0a470c00025f424a`. Even I tried to return `long` instead of `int` – Joaquin Iurchuk Oct 24 '15 at 21:47
  • 1
    In the for loop, just loop through each char in s.toCharArray(). I checked, it's quicker. – NonameSL Aug 02 '16 at 09:17
  • @PeterMortensen Impossible to remember at this moment, have passed 7 years :) I suppose for some inputs did not get always the expected output. – AlexAndro Jun 29 '22 at 13:23
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();
        }
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
TheOraclePhD
  • 83
  • 1
  • 8
3

My way:

private static int hexToDec(String hex) {
    return Integer.parseInt(hex, 16);
}
Denys Lobur
  • 124
  • 5
0
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);
}
Unheilig
  • 16,196
  • 193
  • 68
  • 98
Chandan
  • 9
  • 1
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.
teteArg
  • 3,684
  • 2
  • 20
  • 18
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;
 }
cri_sys
  • 472
  • 1
  • 5
  • 17
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';
}
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

sonnykwe
  • 9
  • 2
0

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

BigInteger("625b", 16)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
-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");

    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
-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);
Deepu
  • 1
-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);
Marcel Bro
  • 4,907
  • 4
  • 43
  • 70