private static String convertToHex(byte[] data) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) {
Up to this point ... only basic setup and starting a loop to go through all the bytes in the array
int halfbyte = (data[i] >>> 4) & 0x0F;
Bytes when converting to hexadecimal are two hexadecimal digits or 8 binary digits, depending on which base you are looking at. The above operator shifts the high 4 bits down (→> - unsigned right shift) and the logical ANDs from 0000 1111, so the result will be an integer equal to the high 4 bits of the byte (the first hexadecimal digit).
Let's say 23 was input, it is 0001 0111 in binary format. The shift makes and logical AND hides it to 0000 0001.
int two_halfs = 0; do {
It just sets the do / while loop to execute twice
if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10)));
Here we show the actual sixth digit, basically just using a zero or a character as a starting point and moving on to the correct character. The first if statement covers all the digits 0-9, and the second covers all the digits 10-15 (af in hexadecimal format)
Again, using our example, 0000 0001 in decimal value is 1. We get to the top if block and add 1 to the character '0' to get the character '1', add it to the string and go to.
halfbyte = data[i] & 0x0F;
Now we will configure an integer to simply combine the low-order bits with the byte and repeat.
Again, if our input was 23 ... 0001 0111 after the logical AND it becomes only 0000 0111, which is 7 decimal. Repeat the same logic as above and the “7” symbol will be displayed.
} while(two_halfs++ < 1);
Now we just go to the next byte in the array and repeat.
} return buf.toString(); }
To answer your next question, the Java API already has a basic conversion utility built into BigInteger. See the documentation for toString (int radix) .
Without knowing the implementation used by the Java API, I cannot say for sure, but I would bet that implementing Java is more efficient than the first somewhat simple algorithm that you published.