matrix.boot.common.encrypt.Hex Maven / Gradle / Ivy
package matrix.boot.common.encrypt;
import matrix.boot.common.exception.ServiceException;
/**
* Hex工具
* @author wangcheng
*/
public class Hex {
/**
* byte转hex字符串
* @param b 字节
* @return hex字符串
*/
public static String byteToHex(byte[] b) {
StringBuilder hs = new StringBuilder();
String stmp;
for (int n = 0; b != null && n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0XFF);
if (stmp.length() == 1) {
hs.append('0');
}
hs.append(stmp);
}
return hs.toString().toUpperCase();
}
/**
* 字符串字byte 转 Hex byte
* @param b 字符串字节
* @return hex byte
*/
public static byte[] hexToByte(byte[] b) {
if ((b.length % 2) != 0) {
throw new ServiceException();
}
byte[] b2 = new byte[b.length / 2];
for (int n = 0; n < b.length; n += 2) {
String item = new String(b, n, 2);
b2[n / 2] = (byte) Integer.parseInt(item, 16);
}
return b2;
}
}