- 基于Bytes数据与字符串之间的互相转换;
- 灵活的设置截取的长度,方便剔除一些标志的字节;
/**
* @author wangyq
*/
public class CustomHexUtils {
/**
* 根据传入的字节数组,返回字符串
* @param length 截取指定长度的数组
*/
public static String getBytes2String(byte[] b, int length) {
StringBuilder stringBuffer = new StringBuilder(512);
for (int i = 0; i < length; ++i) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
stringBuffer.append(hex.toUpperCase());
}
return stringBuffer.toString();
}
/**
* 将字符串转化为二进制byte数组
* @param hex 字符串
*/
public static byte[] hexStringToByte(String hex) {
int len = (hex.length() / 2);
byte[] result = new byte[len];
char[] singleChar = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (toByte(singleChar[pos]) << 4 | toByte(singleChar[pos + 1]));
}
return result;
}
/**
* 字符转byte
* @param c 字符
* @return byte
*/
private static byte toByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
}