Saturday, November 27, 2010

Convert the byte to hex format


public static void main(String[] args)
{
String toHash =
"expire=1290777974mid=2865745secret=blablasid=1fa2773cd5451a627ebe63a6b3f1341b14ab7c5e866b01d808fee30ba2uQpzRxC856eUH5N8viXt";

MessageDigest md = null;
try
{
md = MessageDigest.getInstance("MD5");
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}

byte[] mdbytes = md.digest(toHash.getBytes());

long currentTimeMillis = System.currentTimeMillis();
for (int k = 0; k < 10000; k++)
{
//convert the byte to hex format method 1
StringBuffer sb2 = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++)
{
sb2.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
}
String string = sb2.toString();
// System.out.println("Digest(in hex format) 1 :: " + sb2.toString());
}
currentTimeMillis = System.currentTimeMillis() - currentTimeMillis;
System.out.println(">>> alexey: .main currentTimeMillis = " + currentTimeMillis);

currentTimeMillis = System.currentTimeMillis();
for (int k = 0; k < 10000; k++)
{
//convert the byte to hex format method 2
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < mdbytes.length; i++)
{
String hex = Integer.toHexString(0xff & mdbytes[i]);
if (hex.length() == 1)
hexString.append('0');
hexString.append(hex);
}
String string = hexString.toString();
// System.out.println("Digest(in hex format) 2 :: " + hexString.toString());
}
currentTimeMillis = System.currentTimeMillis() - currentTimeMillis;
System.out.println(">>> alexey: .main currentTimeMillis = " + currentTimeMillis);
}




The result is
>>> alexey: .main currentTimeMillis = 223
>>> alexey: .main currentTimeMillis = 76

No comments: