Byte array to hexadecimal string and character array

Source: Internet
Author: User

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}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.