HexUtil.java
1.52 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
package com.glsx.libble.util;
/**
* @Package: com.glsx.ble_eample.util
* @ClassName: HexUtil
* @Company GLSX
* @Email yangks@didihu.com.cn
* @Description: 作用描述:
* @Author: yangks
* @CreateDate: 2021/4/14 15:53
* @Version:
*/
public class HexUtil {
/**
* 是否是十六进制字符串
*
* @param str
* @return
*/
public static boolean isHexData(String str) {
if (str == null) {
return false;
}
char[] chars = str.toCharArray();
if ((chars.length & 1) != 0) {//个数为奇数,直接返回false
return false;
}
for (char ch : chars) {
if (ch >= '0' && ch <= '9') continue;
if (ch >= 'A' && ch <= 'F') continue;
if (ch >= 'a' && ch <= 'f') continue;
return false;
}
return true;
}
//字符串转byte数组
public static byte[] hexToByteArray(String inHex) {
int hexlen = inHex.length();
byte[] result;
if (hexlen % 2 == 1) {
//奇数
hexlen++;
result = new byte[(hexlen / 2)];
inHex = "0" + inHex;
} else {
//偶数
result = new byte[(hexlen / 2)];
}
int j = 0;
for (int i = 0; i < hexlen; i += 2) {
result[j] = hexToByte(inHex.substring(i, i + 2));
j++;
}
return result;
}
private static byte hexToByte(String inHex) {
return (byte) Integer.parseInt(inHex, 16);
}
}