This week's book giveaway is in the OCAJP forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide 1Z0-808 and have Jeanne Boyarsky & Scott Selikoff on-line! See this thread for details.
I'm trying to convert a Java byte to a 2-digit Hex string hex string. I can use the System output to get what I want, but I'm having trouble writing a general method.
In short, I'm looking for the equivalent of doing the following:
..but with the ability to append the results to a StringBuilder/StringBuffer object. Any suggestions? I searched online a bit but the examples I came across included manually converting byte values which seemed a bit excessive. I'm assuming there's something in the API to simplify this in a one-line call.
This is very very easy. Class java.util.Formatter has an constructor that allows one to specify an Appendable. You can then us the format() method to write values into that Appendable. Both StringBuidler and StringBuffer implement Appendable.
Thanks, James. Using a Formatter by passing a StringBuilder to it is efficient, because the Formatter directly writes to the StringBuilder, so strings don't have to be copied, which is useful especially if you have to format for example a byte to hex characters. I needed this today, here's what I wrote:
I don't like returning a String unless I need a String so if I were doing this I would probably overload the method along the lines of -
As an aside - I'm never sure whether it is more efficient to index an array of primitives or iterate over it. Since the second parameter to the format() method is a varags Object it probably makes no difference her since an Integer or Byte wrapper will be created anyway. I suspect that the cost of having to parse the "%02x" greatly outweighs any cost of creating the wrappers.
If you just want to format one byte into a pair of hex digits, then String.format("%02X", b); is ofcourse the only thing you need. But our last few posts were about what if you have an array of bytes that you want to convert to a string of hex characters.
For short term use, String.format should definitely be used. James' and my solutions are minor optimizations that will only make sense if called a lot and/or if you have limited resources. James' solution creates a new Formatter each time, mine doesn't. That's the only difference between the two.