user3514540 user3514540 - 1 year ago 125
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 Source

You should use Integer.decode() instead of Integer.parseInt() as it handles hex strings as well. See;

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download