Skip to content

Instantly share code, notes, and snippets.

@antic-ml
Created September 6, 2020 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antic-ml/6f1c7e166ff11c527feae2d4c546581e to your computer and use it in GitHub Desktop.
Save antic-ml/6f1c7e166ff11c527feae2d4c546581e to your computer and use it in GitHub Desktop.
Convert hex to decimal
import java.text.NumberFormat;
public class Hex2Dec {
public static int hexToDec(String hex) {
String hexStr = hex.toUpperCase();
if( hexStr.startsWith(("0x")))
hexStr = hexStr.substring(2,hexStr.length()-1);
int len = hexStr.length();
int power = 0;
int value = 0;
for(int i=0; i<hexStr.length(); i++) {
char c = hexStr.charAt(i);
power = (int)Math.pow(16, len - 1);
if( c >='0' && c <='9' )
value += power * (c - 48);
else if( c >='A' && c <= 'F' )
value += power * (c - 65 + 10);
len--;
}
return value;
}
public static void main(String[] args) {
if( args.length == 0 ) {
System.out.println("Usage: java Hex2Dec <hex number>");
return;
}
String hex = args[0];
int value = hexToDec(hex);
String valStr = NumberFormat.getInstance().format(value);
System.out.println("0x" + hex.toUpperCase() + " = " + valStr);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment