在与硬件设备通信的时候,硬件传回来的数据经常是十六进制的,在0-100的范围内java会自动转换成十进制的数字出来,但如果包含abc这些字符自动转换就有问题了,可能变成负数了。下面提供两个方法转换成十六进制的 可以输出和设备传的时候一样的内容(可能字母大小写变了,在设备里大写的输出是小写的)。
2
3 public class CommonUtil {
4 /**
5 * byte数组转换成16进制字符串
6 * @param src
7 * @return
8 */
9 public static String bytesToHexString(byte[] src){
10 StringBuilder stringBuilder = new StringBuilder();
11 if (src == null || src.length <= 0) {
12 return null;
13 }
14 for (int i = 0; i < src.length; i++) {
15 int v = src[i] & 0xFF;
16 String hv = Integer.toHexString(v);
17 if (hv.length() < 2) {
18 stringBuilder.append(0);
19 }
20 stringBuilder.append(hv);
21 }
22 return stringBuilder.toString();
23 }
24
25 /**
26 * byte数组转换成16进制字符数组
27 * @param src
28 * @return
29 */
30 public static String[] bytesToHexStrings(byte[] src){
31 if (src == null || src.length <= 0) {
32 return null;
33 }
34 String[] str = new String[src.length];
35
36 for (int i = 0; i < src.length; i++) {
37 int v = src[i] & 0xFF;
38 String hv = Integer.toHexString(v);
39 if (hv.length() < 2) {
40 str[i] = "0";
41 }
42 str[i] = hv;
43 }
44 return str;
45 }
46
47 }
3 public class CommonUtil {
4 /**
5 * byte数组转换成16进制字符串
6 * @param src
7 * @return
8 */
9 public static String bytesToHexString(byte[] src){
10 StringBuilder stringBuilder = new StringBuilder();
11 if (src == null || src.length <= 0) {
12 return null;
13 }
14 for (int i = 0; i < src.length; i++) {
15 int v = src[i] & 0xFF;
16 String hv = Integer.toHexString(v);
17 if (hv.length() < 2) {
18 stringBuilder.append(0);
19 }
20 stringBuilder.append(hv);
21 }
22 return stringBuilder.toString();
23 }
24
25 /**
26 * byte数组转换成16进制字符数组
27 * @param src
28 * @return
29 */
30 public static String[] bytesToHexStrings(byte[] src){
31 if (src == null || src.length <= 0) {
32 return null;
33 }
34 String[] str = new String[src.length];
35
36 for (int i = 0; i < src.length; i++) {
37 int v = src[i] & 0xFF;
38 String hv = Integer.toHexString(v);
39 if (hv.length() < 2) {
40 str[i] = "0";
41 }
42 str[i] = hv;
43 }
44 return str;
45 }
46
47 }