Converting some hexadecimal string to a decimal integer

130,999

Solution 1

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.

Solution 2

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

My way:

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

Solution 5

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';
}
Share:
130,999

Related videos on Youtube

vontarro
Author by

vontarro

Updated on May 12, 2022

Comments

  • vontarro
    vontarro almost 2 years

    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()));
        }
    }
    
    • stevevls
      stevevls over 10 years
      Don't forget that hex is case insensitive, so you should check for capital A-F as well.
    • scottb
      scottb over 10 years
      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.
    • Peter Mortensen
      Peter Mortensen almost 2 years
      There is a lot of redundancy in it (and inefficiency). display.getText() is repeated 12 times.
    • Peter Mortensen
      Peter Mortensen almost 2 years
      This question is now attracting answers that reinvent the wheel (only the title of the question is read before answering). This question already uses Integer.parseInt(display.getText(), 16); for the conversion!!!!
  • Kevin Bowersox
    Kevin Bowersox over 10 years
    Good catch! Never would have seen that.
  • Joaquin Iurchuk
    Joaquin Iurchuk over 8 years
    Doesn't work for me. I tried to passing it the String number 0a470c00025f424a. Even I tried to return long instead of int
  • NonameSL
    NonameSL over 7 years
    In the for loop, just loop through each char in s.toCharArray(). I checked, it's quicker.
  • Sunil Garg
    Sunil Garg about 6 years
    Please provide some explanation
  • Deepu
    Deepu over 5 years
    I simplify the solution.
  • Peter Mortensen
    Peter Mortensen almost 2 years
    That is a lot of redundancy. Isn't there an easier way?
  • Peter Mortensen
    Peter Mortensen almost 2 years
    What do you mean by "didn't always work for me"? For upper and lower case hexadecimal notation ('a'-'f' and 'A'-'F' )?
  • Peter Mortensen
    Peter Mortensen almost 2 years
    That doesn't seem credible. It seems like a completely bogus answer. Can you explain your solution, please (including linking to documentation)? Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).
  • Peter Mortensen
    Peter Mortensen almost 2 years
    That is a lot of redundancy. Isn't there an easier way?
  • Peter Mortensen
    Peter Mortensen almost 2 years
    But it doesn't answer the question. Sample input was string "100a" and "625b".
  • Peter Mortensen
    Peter Mortensen almost 2 years
    But that is already used in the question. The real problem was the leading space in the string (solved 3 1/2 years prior).
  • Peter Mortensen
    Peter Mortensen almost 2 years
    But the question was not about implementing the conversion. That is already in Java (the question used Integer.parseInt(hex, 16).)
  • Peter Mortensen
    Peter Mortensen almost 2 years
    But the question was not about implementing the conversion. That is already in Java (the question used Integer.parseInt(hex, 16).). And it doesn't answer the question. Sample input was string "100a" and "625b".
  • Peter Mortensen
    Peter Mortensen almost 2 years
    But the question was not about implementing the conversion. That is already in Java (the question used Integer.parseInt(hex, 16).).
  • Peter Mortensen
    Peter Mortensen almost 2 years
    But the question was not about implementing the conversion. That is already in Java (the question used Integer.parseInt(hex, 16).).
  • Peter Mortensen
    Peter Mortensen almost 2 years
    What is BigInteger? At least link to the documentation (as a non-naked link). Part of some library? Built-in? What is the minimum Java version? Please respond by editing (changing) your answer, not here in comments (without "Edit:", "Update:", or similar - the answer should appear as if it was written today).
  • Stefan Emanuelsson
    Stefan Emanuelsson almost 2 years
    @PeterMortensen BigInteger is standard java. Find yourself a better hobby
  • AlexAndro
    AlexAndro almost 2 years
    @PeterMortensen Impossible to remember at this moment, have passed 7 years :) I suppose for some inputs did not get always the expected output.