最近项目中需要把字节数组转换为十六进制数的形式,研究了好久终于实现了,分享一下 转载自:FX_SKY的博客
字节数组与十六进制字符串之间的相互转换
- /**
- * Convert byte[] to hex
- * string.这里我们可以将byte转换成int,然后利用Integer.toHexString(int)来转换成16进制字符串。
- * @param src
- * @return
- */
- public String bytesToHexString(byte[] src) {
- StringBuilder stringBuilder = new StringBuilder("");
- if (src == null || src.length <= 0) {
- return null;
- }
- for (int i = 0; i < src.length; i++) {
- int v = src[i] & 0xFF;
- String hv = Integer.toHexString(v);
- if (hv.length() < 2) {
- stringBuilder.append(0);
- }
- stringBuilder.append(hv);
- }
- return stringBuilder.toString();
- }
- /**
- * Convert hex string to byte[]
- *
- * @param hexString
- * @return
- */
- public byte[] hexStringToBytes(String hexString) {
- if (hexString == null || hexString.equals("")) {
- return null;
- }
- // hexString = hexString.toUpperCase(); //如果是大写形式
- int length = hexString.length() / 2;
- char[] hexChars = hexString.toCharArray();
- byte[] d = new byte[length];
- for (int i = 0; i < length; i++) {
- int pos = i * 2;
- d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
- }
- return d;
- }
- private byte charToByte(char c) {
- return (byte) "0123456789abcdef".indexOf(c);
- // return (byte) "0123456789ABCDEF".indexOf(c);
- }
/**
* Convert byte[] to hex
* string.这里我们可以将byte转换成int,然后利用Integer.toHexString(int)来转换成16进制字符串。
* @param src
* @return
*/
public String bytesToHexString(byte[] src) {
StringBuilder stringBuilder = new StringBuilder("");
if (src == null || src.length <= 0) {
return null;
}
for (int i = 0; i < src.length; i++) {
int v = src[i] & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString();
}
/**
* Convert hex string to byte[]
*
* @param hexString
* @return
*/
public byte[] hexStringToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
//hexString = hexString.toUpperCase();//如果是大写形式
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
private byte charToByte(char c) {
return (byte) "0123456789abcdef".indexOf(c);
//return (byte) "0123456789ABCDEF".indexOf(c);
}