Repository navigation
Expand file tree
/
Copy pathHex.java
More file actions
65 lines (56 loc) · 1.49 KB
/
Copy pathHex.java
File metadata and controls
65 lines (56 loc) · 1.49 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package com.java.alogrithm.utils;
/**
* HEX字符串与字节码转换工具
*
* @author steven-pan
*
*/
public class Hex {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
System.out.println("HEX编解码测试:");
final String input = "01234567890abcdefghijklmnopqrstuvwxyz";
System.out.println("编码前:" + input);
String hex = encode(input.getBytes("UTF-8"));
System.out.println("HEX format:" + hex);
byte[] hexbytes = deocde(hex);
System.out.println("解密后:" + new String(hexbytes, "UTF-8"));
}
/**
* 将16进制转换为二进制(服务端)
*
* @param hexStr
* @return
*/
public static byte[] deocde(String hexStr) {
if (hexStr.length() < 1)
return null;
byte[] result = new byte[hexStr.length() / 2];
for (int i = 0; i < hexStr.length() / 2; i++) {
int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
result[i] = (byte) (high * 16 + low);
}
return result;
}
/**
* 将二进制转换成16进制
*
* @param buf
* @return
*/
public static String encode(byte buf[]) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < buf.length; i++) {
String hex = Integer.toHexString(buf[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
sb.append(hex.toUpperCase());
}
return sb.toString();
}
}