byte[] 以16进制形式的输出的方法
- 方式一 Integer.toHexString()
public static String printHexString(byte[] b) {
String res = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
res += hex;
}
return res;
}
- 方式二 formatter.format()
public static String byte2HexString(byte[] bb, int index, boolean isUpperCase) {
if (null == bb || bb.length == 0) {
return "";
}
String hexStr = "";
String formatterStr = "%02X";
Formatter formatter = new Formatter();
if (isUpperCase) {
formatterStr = "%02X";
} else {
formatterStr = "%02x";
}
for (int i = index; i < bb.length; i++) {
hexStr = formatter.format(formatterStr, bb[i]).toString();
}
return hexStr;
}
16进制形式的字符转成byte[]
public static byte[] hexStringToByte(String hex) {
byte[] result = null;
if (null == hex) {
return result;
}
hex = hex.toUpperCase();
final String HEX_NUMS_STR = "0123456789ABCDEF";
int len = (hex.length() / 2);
result = new byte[len];
char[] hexChars = hex.toCharArray();
for (int i = 0; i < len; i++) {
int pos = i * 2;
result[i] = (byte) (HEX_NUMS_STR.indexOf(hexChars[pos]) << 4 | HEX_NUMS_STR.indexOf(hexChars[pos + 1]));
}
return result;
}
网友评论