- 基于Bytes數(shù)據(jù)與字符串之間的互相轉(zhuǎn)換贞滨;
- 靈活的設(shè)置截取的長(zhǎng)度,方便剔除一些標(biāo)志的字節(jié);
/**
* @author wangyq
*/
public class CustomHexUtils {
/**
* 根據(jù)傳入的字節(jié)數(shù)組,返回字符串
* @param length 截取指定長(zhǎng)度的數(shù)組
*/
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();
}
/**
* 將字符串轉(zhuǎn)化為二進(jìn)制byte數(shù)組
* @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;
}
/**
* 字符轉(zhuǎn)byte
* @param c 字符
* @return byte
*/
private static byte toByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
}
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者