Thursday, April 22, 2010

Java Code For Binary Hexadecimal Conversion

In this post code for binary to hex coversion has been posted. This is pure java code and can be used in BlackBerry, J2ME and Java.

/**
* This class provides funcationlity to convert binary byte array to hexadecimal byte array as
* well as to convert hexadecimal byte array to binary byte array.
*/
public class BinHexConverter
{
private static String HEX_STRING = "0123456789ABCDEF";

public static byte[] convertHexToBinary(byte[] hex)
{
int block = 0;

byte[] data = new byte[hex.length / 2];

int index = 0;
boolean next = false;

for (int i=0; i<<= 4; int pos = HEX_STRING.indexOf(Character.toUpperCase((char) hex[i])); if (pos > -1)
{
block += pos;
}

if (next)
{
data[index] = (byte)(block & 0xff );
index++;
next = false;
}
else
{
next = true;
}
}

return data;
}

private static String convertBinary2Hex(byte[] binary)
{
StringBuffer buf = new StringBuffer();

int block = 0;

for (int i=0; i> 4));
buf.append(HEX_STRING.charAt(binary[i] & 0x0F));
}

return buf.toString();
}
}

/**
* Test class for binary to hex conversion.
*/
public class BinHexTester
{
public static void main(String[] args)
{
String strText = BinHexConverter.convertBinary2Hex("hellohello".getBytes());
System.out.println(strText);
}
}

No comments: