In many cases, we need to convert byte arrays into hexadecimal strings for storage, especially in many encryption scenarios, such as saving keys. In addition to writing data to a file or writing data to a database in binary format, the byte array cannot be directly converted to a string because \ 0 exists at the end of the string. Of course, there must be other reasons.
The following solutions are used in Java:
Solution 1: The BigInteger method should be the simplest solution.
/*** Use the signature helper class to convert the String byte array * @ param str * @ return */public static byte [] md5 (String str) {byte [] digest = null; try {MessageDigest md = MessageDigest. getInstance ("md5"); return digest = md. digest (str. getBytes ();} catch (NoSuchAlgorithmException e) {e. printStackTrace ();} return null;}/*** method 1 ** @ param bytes * @ return */public static String bytes2hex01 (byte [] bytes) {/*** for the explanation of the first parameter, remember to set it to 1 * signum of the number (-1 for negative, 0 for zero, 1 for positive ). */BigInteger bigInteger = new BigInteger (1, bytes); return bigInteger. toString (16 );}
Solution 2: perform operations on each byte and 0xFF, convert it to hexadecimal, and then convert it to hexadecimal by using Integer.
/*** Method 2 ** @ param bytes * @ return */public static String bytes2hex02 (byte [] bytes) {StringBuilder sb = new StringBuilder (); String tmp = null; for (byte B: bytes) {// calculate each byte and 0xFF, convert it to hexadecimal, and then convert it to hexadecimal tmp = Integer by Integer. toHexString (0xFF & B); if (tmp. length () = 1) // each byte is 8, converted to a hexadecimal flag, two hexadecimal bits {tmp = "0" + tmp;} sb. append (tmp);} return sb. toString ();}
Solution 3: retrieve the four-byte and four-byte values, and then obtain the values from the 10th to 0-15 respectively. Then, use a string array to complete the process perfectly. The third method is recommended for understanding the conversion.
/*** Method 3 ** @ param bytes * @ return */public static String bytes2hex03 (byte [] bytes) {final String HEX = "0123456789 abcdef "; stringBuilder sb = new StringBuilder (bytes. length * 2); for (byte B: bytes) {// retrieves the 4-bit high of this byte, and then computes it with 0x0f to obtain a data between 0 and 15, through HEX. charAt (0-15) is a hexadecimal number sb. append (HEX. charAt (B> 4) & 0x0f); // retrieves the low position of this byte, and returns the data between 0 and 15 through HEX. charAt (0-15) is a hexadecimal number sb. append (HEX. charAt (B & 0x0f);} return sb. toString ();}