[java] Converting Hexadecimal String to 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 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)

Do you have any idea how can I convert my string with letters to 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()));
    }
}

This question is related to java hex type-conversion

The answer is


Google got me here, so i am updating this late for other to find when searching. A much simpler way is to use BigInteger, like so:

BigInteger("625b", 16)

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

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

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

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

Given a hexadecimal number

K?K??1K??2....K2K1K0

The equivalent decimal value is:

K? * 16? + K??1 * 16??1 + K??2 * 16??2 + .... + K2 * 162 + K1 * 161 + K0 * 160

For example, the hex number AB8C is:

10 * 163 + 11 * 162 + 8 * 161 + 12 * 160 = 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';
}

Well, Mr.ajb has resolved and pointed out the error in your code.

Coming to the second part of the code, that is, converting a string with letters to decimal integer below is code for that,

import java.util.Scanner;

public class HexaToDecimal
{
   int number;

   void getValue()
   {
      Scanner sc = new Scanner(System.in);
      System.out.println("Please enter hexadecimal to convert: ");
      number = Integer.parseInt(sc.nextLine(), 16);
      sc.close();
   }

   void toConvert()
   {
      String decimal = Integer.toString(number);
      System.out.println("The Decimal value is : " + decimal);
   }

   public static void main(String[] args)
   {
      HexaToDecimal htd = new HexaToDecimal();
      htd.getValue();
      htd.toConvert();
   }
}

You can refer example on hexadecimal to decimal for more information.


//package com.javatutorialhq.tutorial;

import java.util.Scanner;

/* * Java code 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 hex 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 hex number

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

        }

        finally{ s.close();

        }
    } 
}

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


My way:

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

  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 over the internet. Some of the others solutions provided here didn't always work for me.


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

} }


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

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.

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to hex

Transparent ARGB hex value How to convert a hex string to hex number Javascript: Unicode string to hex Converting Hexadecimal String to Decimal Integer Convert string to hex-string in C# Print a variable in hexadecimal in Python Convert ascii char[] to hexadecimal char[] in C Hex transparency in colors printf() formatting for hex Python Hexadecimal

Examples related to type-conversion

How can I convert a char to int in Java? pandas dataframe convert column type to string or categorical How to convert an Object {} to an Array [] of key-value pairs in JavaScript convert string to number node.js Ruby: How to convert a string to boolean Convert bytes to int? Convert dataframe column to 1 or 0 for "true"/"false" values and assign to dataframe SQL Server: Error converting data type nvarchar to numeric How do I convert a Python 3 byte-string variable into a regular string? Leading zeros for Int in Swift