user3514540 user3514540 - 13 days ago 9
Java Question

Number format exception in Java: unknown hex number

I`m working on a project and I had to convert a hex String to a binary String I used a lot of methods but the code below was the most useful to me although this code creates an unknown hex number "l" which looks like 1 but is not one, does some one know what this thing is(l)? and how did it appear and how to fix it and convert it to "1" ?

public String hexToBin(String hex){
String bin =new String();
String binFragment =new String();
int iHex;
hex = hex.trim();
hex = hex.replaceFirst("0x","");

for(int i = 0; i < hex.length(); i++){
iHex = Integer.parseInt(""+hex.charAt(i),16);
binFragment = Integer.toBinaryString(iHex);

while(binFragment.length() < 4){
binFragment = "0" + binFragment;
}
bin += binFragment;
}

Answer

You should use Integer.decode() instead of Integer.parseInt() as it handles hex strings as well. See; http://docs.oracle.com/javase/7/docs/api/java/lang/Integer.html#decode(java.lang.String)