Created
September 6, 2020 17:45
-
-
Save antic-ml/6f1c7e166ff11c527feae2d4c546581e to your computer and use it in GitHub Desktop.
Convert hex to decimal
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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