JAVA常见编码转换

1.UTF-8转换byte[]

1
2
3
4
5
6
7
8
9
10
import java.nio.charset.StandardCharsets;

// UTF-8 -》 二进制
String utf8str = "Hello, Admin!"
byte[] Bytes = utf8str.getBytes(StandardCharsets.UTF_8);
//byte[] bytes3 = utf8str.getBytes();
System.out.println(Arrays.toString(bytes));
// 二进制 -》 UTF-8
String utf8str = new String(Bytes, StandardCharsets.UTF_8);
System.out.println(utf8str);
  • 前端部分
1
2
let bufferKey = Buffer.from(key, "utf8")
key = bufferKey.toString('utf8')

2.BASE64字符串转换byte[]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import java.util.Base64;


String base64String = "SGVsbG8sIFNNNCE=";
byte[] Bytes = Base64.getDecoder().decode(base64String);
System.out.println(Arrays.toString(bytes));

base64str = Base64.getEncoder().encodeToString(Bytes);
System.out.println(base64str);

//hultool
//import cn.hutool.core.codec.Base64;
byte[] Bytes = Base64.decode(cipherTxt);
System.out.println(Arrays.toString(bytes));
String base64 = Base64.encode(bytes);
System.out.println(base64);
  • 前端部分
1
2
let bufferKey = Buffer.from(key, "base64")
key = bufferKey.toString('base64')

3.Hex转换byte[]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
//自实现 

//------------hexString To Bytes
public static byte[] hexStringToBytes(String hexString) {
int len = hexString.length();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
+ Character.digit(hexString.charAt(i+1), 16));
}
return data;
}

String str3 = "admin123"
byte[] bytes3= hexStringToBytes(str3)
System.out.println(Arrays.toString(bytes3));

//----------------Bytes To hexString
public static String BytesTohexString(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
String hex = Integer.toHexString(0xFF & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}

// commons-codec
// 将字节流转换为十六进制字符串
byte[] bytes2 = "Hello, World!".getBytes();
String hexString2 = Hex.encodeHexString(bytes2);
System.out.println(hexString2);

// 将十六进制字符串转换为字节流
byte[] decodedBytes = Hex.decodeHex(hexString2);
System.out.println(new String(decodedBytes));


// hultool
import cn.hutool.core.util.HexUtil;

String hexstr = "626c353233597339364a6b4b79304564";
//hex to bin
byte[] Bytes = HexUtil.decodeHex(hexstr);
System.out.println(Arrays.toString(Bytes));
//bin to hex
String hexstr2 = HexUtil.encodeHexStr(Bytes);
System.out.println(hexstr2);
  • 前端部分
1
2
let bufferKey = Buffer.from(key, "hex")
key = bufferKey.toString('hex')