Many times we need to convert a byte array into a 16 binary string to save, such as when I am I/O byte stream operation, especially in a lot of encrypted scenes application is more extensive.
In Java, Byte uses a binary representation of 8 bits, and we know that each character of the 16 binary needs to be represented by a 4-bit bits, so we can convert each byte to two corresponding 16 characters, that is, the high 4-bit and low 4 bits of byte are converted to the corresponding 16-character H and L, respectively. and combine to get the result of a byte conversion to a 16 binary string new string (H) + new String (L). That is, byte represents only 2 bits in hexadecimal notation.
As can be seen from the above we only need to remove the high four-bit and low four-bit binary values, and then the corresponding conversion.
The specific options are as follows:
/** * 0x0F hexadecimal f equals value decimal 15, Binary representation of 0000 1111 binary 1 & any number is the original number binary 0 & any number is 0 * * @param b * @return */ public static String bytetohexstring (byte b) { final string hex = "0123456789abcdef"; stringbuilder sb = new stringbuilder (); /** * why with 0xof arithmetic because the binary of 0xof is 0000 1111, while the 1& operation obtains the original number, 0 The & Operation concludes 0 */ // 1. Remove the high four-bit value of byte B and append // the high four-bit to the right four-bit, and the 0x0f operation results in a high four-bit value sb.append (Hex.charat ((b >> 4) & 0x0f)); // 2. Remove the low four-bit value and append // direct to The 0x0f operation results in a low four-bit numeric sb.append (Hex.charat (b & 0x0f)); return sb.tostring (); }
Summarized as follows:
(1) A byte corresponds to a two-bit hexadecimal bit instead of a eight-bit (32-bit bits);
(2) After the conversion to hexadecimal, less than two, the high level to fill 0.
This article is from the "Wang Wei" blog, make sure to keep this source http://jaydenwang.blog.51cto.com/6033165/1746161
Java converts bytes to 16 binary strings