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