[b][color=red]开发者博客:[url]http://www.developsearch.com[/url][/color][/b]
/**
* 字节转化工具类
*
* @author chenxin
* @version [版本号, 2012-5-21]
* @see [相关类/方法]
* @since [产品/模块版本]
*/
public class ByteUtil {
/**
* 把16进制字符串转换成字节数组
* <功能详细描述>
* @param hex String
* @return byte[]
* @see [类、类#方法、类#成员]
*/
public static byte[] hexString2Bytes(String hex)
{
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] achar = hex.toCharArray();
for (int i = 0; i < len; i++)
{
int pos = i * 2;
result[i] = (byte)(char2Byte(achar[pos]) << 4 | char2Byte(achar[pos + 1]));
}
return result;
}
private static byte char2Byte(char ch)
{
switch (ch)
{
case '0':
return 0x00;
case '1':
return 0x01;
case '2':
return 0x02;
case '3':
return 0x03;
case '4':
return 0x04;
case '5':
return 0x05;
case '6':
return 0x06;
case '7':
return 0x07;
case '8':
return 0x08;
case '9':
return 0x09;
case 'a':
return 0x0A;
case 'b':
return 0x0B;
case 'c':
return 0x0C;
case 'd':
return 0x0D;
case 'e':
return 0x0E;
case 'f':
return 0x0F;
}
return 0x00;
}
/**
* 字节数组 转化成 16进制字符串
* <功能详细描述>
* @param b byte[]
* @return String
* @see [类、类#方法、类#成员]
*/
public static String bytes2hexString(byte[] b)
{
String stmp = null;
StringBuffer buf = new StringBuffer();
for (int n = 0; n < b.length; n++)
{
stmp = Integer.toHexString(b[n] & 0xff);
if (1 == stmp.length())
{
stmp = "0" + stmp;
}
buf.append(stmp);
}
return buf.toString();
}
// 整数到字节数组转换
public static byte[] int2bytes(int n)
{
byte[] ab = new byte[4];
ab[0] = (byte)(0xff & n);
ab[1] = (byte)((0xff00 & n) >> 8);
ab[2] = (byte)((0xff0000 & n) >> 16);
ab[3] = (byte)((0xff000000 & n) >> 24);
return ab;
}
// 字节数组到整数的转换
public static int bytes2int(byte b[])
{
int s = 0;
s = ((((b[0] & 0xff) << 8 | (b[1] & 0xff)) << 8) | (b[2] & 0xff)) << 8 | (b[3] & 0xff);
return s;
}
// 字节转换到字符
public static char byte2char(byte b)
{
return (char)b;
}
}