之前就写了一个
将基本数据类型转换成十六进制字符串的工具类,回头看了一下感觉有点复杂,今天写了一个易懂的,而且性能也不错。
package eli.util;


/** *//**
* 将数字转换成十六进制数字的工具类。
* <p>
* 相比{@link HexUtil}的代码,这个类更易于理解,性能差异却很小。
*
* @author <a href="mailto:eli.wuhan@gmail.com">屹砾</a>
*/

public class HexConvert
{

protected static final char[] CHAR =
{ '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };


protected static String toHex(long value, int bytes)
{
int max = (bytes << 1) - 1;
char[] chars = new char[bytes << 1];

for (int i = (bytes << 1) - 1; i >= 0; i--)
{
chars[max - i] = CHAR[(int) ((value >> (4 * i)) & 0xF)];
}
return new String(chars);
}


public static String toHex(byte value)
{
return toHex(value, 1);
}


public static String toHex(char value)
{
return toHex(value, 2);
}


public static String toHex(short value)
{
return toHex(value, 2);
}


public static String toHex(int value)
{
return toHex(value, 4);
}


public static String toHex(long value)
{
return toHex(value, 8);
}


public static String toHex(byte[] value)
{
StringBuffer buf = new StringBuffer();

for (int i = 0; i < value.length; i++)
{
buf.append(toHex(value[i]));
}
return buf.toString();
}


public static String toHex(char[] value)
{
StringBuffer buf = new StringBuffer();

for (int i = 0; i < value.length; i++)
{
buf.append(toHex(value[i]));
}
return buf.toString();
}

}
