Converting Hexadecimal String to Decimal Integer
It looks like there's an extra space character in your string. 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.
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.
//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();
}
}
}