During communication with hardware devices, the data transmitted from the hardware is often in hexadecimal format. in the range of 0 to, Java will automatically convert it to a decimal number, however, if the characters including ABC are automatically converted, the conversion may be negative. The following two methods are provided to convert the data to hexadecimal format and output the same content as the data transmitted by the device (the uppercase and lowercase letters may change, and the output in the device is lowercase ).
2
3 Public class commonutil {
4 /**
5 * convert byte array to hexadecimal string
6 * @ Param SRC
7 * @ return
8 */
9 public static string bytestohexstring (byte [] SRC ){
10 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 array to hexadecimal character array
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}