byte[] 转16进制字符串
public class Test {
public static void main(String[] args) {
String str = "你好";
System.out.println(bytesToHexFun1(str.getBytes()));
System.out.println(bytesToHexFun2(str.getBytes()));
System.out.println(bytesToHexFun3(str.getBytes()));
System.out.println(bytes_String16Fun1(str.getBytes()));
System.out.println(bytes_String16Fun2(str.getBytes()));
System.out.println(bytesToHex(str.getBytes()));
}
private final static char[] HEX_CHAR = "0123456789ABCDEF".toCharArray();
public static String bytes_String16Fun1(byte[] b) {
StringBuilder sb = new StringBuilder();
for (byte value : b) {
sb.append(HEX_CHAR[value >> 4 & 0xf])
.append(HEX_CHAR[value & 0xf]);
}
return sb.toString();
}
public static String bytes_String16Fun2(byte[] b) {
StringBuilder sb = new StringBuilder();
for (byte value : b) {
sb.append(String.format("%02x", value));
}
return sb.toString();
}
public static String bytesToHexFun1(byte[] bytes) {
char[] buf = new char[bytes.length * 2];
int a = 0;
int index = 0;
for (byte b : bytes) {
if (b < 0) {
a = 256 + b;
} else {
a = b;
}
buf[index++] = HEX_CHAR[a / 16];
buf[index++] = HEX_CHAR[a % 16];
}
return new String(buf);
}
public static String bytesToHexFun2(byte[] bytes) {
char[] buf = new char[bytes.length * 2];
int index = 0;
for (byte b : bytes) {
buf[index++] = HEX_CHAR[b >>> 4 & 0xf];
buf[index++] = HEX_CHAR[b & 0xf];
}
return new String(buf);
}
public static String bytesToHexFun3(byte[] bytes) {
StringBuilder buf = new StringBuilder(bytes.length * 2);
for (byte b : bytes) {
buf.append(String.format("%02x", b & 0xff));
}
return buf.toString();
}
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_CHAR[v >>> 4];
hexChars[j * 2 + 1] = HEX_CHAR[v & 0x0F];
}
return new String(hexChars);
}
public static byte[] stringToBytes(String str) {
if (str == null || str.trim().equals("")) {
return new byte[0];
}
byte[] bytes = new byte[str.length() / 2];
for (int i = 0; i < str.length() / 2; i++) {
String subStr = str.substring(i * 2, i * 2 + 2);
bytes[i] = (byte) Integer.parseInt(subStr, 16);
}
return bytes;
}
}
字节数组的打印
import java.util.Arrays;
public class Test2 {
public static void main(String[] args) {
Byte[] bs1 = {0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F};
System.out.println(Arrays.toString(bs1));
byte[] bs2 = hexStringToByteArray("e04fd020ea3a6910a2d808002b30309d");
System.out.println(Arrays.toString(bs2));
byte[] bs3 = "你好,这是一段字符串!".getBytes();
System.out.println(Arrays.toString(bs3));
}
public static byte[] hexStringToByteArray(String s) {
int len = s.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) +
Character.digit(s.charAt(i + 1), 16));
}
return data;
}
}