In Java, byte uses binary representation to occupy 8 bits, and we know that each character in hexadecimal format needs to be expressed in 4 bits (23
+ 22
+ 21
+ 20
= 15), so we can convert each byte into two hexadecimal characters, that is, the byte's 4-bit high and 4-bit low are converted into the corresponding hexadecimal characters H and l, respectively, and combine them to get the result of byte conversion to a hex string new string (h) + new string (l ).
Similarly, the opposite conversion is to convert two hexadecimal characters into a byte, the same principle as above.
Based on the above principle, we can convert the byte [] array to a hexadecimal string. Of course, we can also convert the hexadecimal string to a byte [] array.
/** <Br/> * convert byte [] to hex string. here we can convert byte to int and then use integer. tohexstring (INT) to convert to a hexadecimal string. <Br/> * @ Param SRC byte [] data <br/> * @ return hex string <br/> */<br/> Public static string bytestohexstring (byte [] SRC) {<br/> stringbuilder = new stringbuilder (""); <br/> If (src = NULL | SRC. length <= 0) {<br/> return NULL; <br/>}< br/> for (INT I = 0; I <SRC. length; I ++) {<br/> int v = SRC [I] & 0xff; <br/> string HV = integer. tohexstring (V); <br/> If (HV. length () <2) {<br/> stringbuilder. append (0); <br/>}< br/> stringbuilder. append (HV); <br/>}< br/> return stringbuilder. tostring (); <br/>}< br/>/** <br/> * Convert hex string to byte [] <br/> * @ Param hexstring the hex string <br/> * @ return byte [] <br/> */<br/> Public static byte [] hexstringtobytes (string hexstring) {<br/> If (hexstring = NULL | hexstring. equals ("") {<br/> return NULL; <br/>}< br/> hexstring = hexstring. touppercase (); <br/> int length = hexstring. length ()/2; <br/> char [] hexchars = hexstring. tochararray (); <br/> byte [] d = new byte [length]; <br/> for (INT I = 0; I <length; I ++) {<br/> int Pos = I * 2; <br/> d [I] = (byte) (chartobyte (hexchars [POS]) <4 | chartobyte (hexchars [POS + 1]); <br/>}< br/> return D; <br/>}< br/>/** <br/> * convert Char to byte <br/> * @ Param C char <br/> * @ return byte <br /> */<br/> private byte chartobyte (char C) {<br/> return (byte) "0123456789 abcdef ". indexof (c); <br/>}
Remarks: AboutCodeIf you have any questions, you can see why the conversion between byte and INT in Java and the operation of 0xff