Reputation: 29
I'm learning how to use java's Formatter class. I'd like to convert a positive byte to a hexadecimal number, then parse it into a String with two digits.
My method would look something like this:
String toHexString(byte byteToConvert) {
StringBuilder hexBuilder = new StringBuilder();
hexBuilder.append(Integer.toHexString(byteToConvert));
return hexBuilder.toString();
}
Is there a way to be able to format the String (or the StringBuilder) to get two digits?
System.out.println(toHexString(127)); // Would like it to output "7f"
System.out.println(toHexString(1)); // Would like it to output "01"
Upvotes: 1
Views: 540
Reputation: 311528
You don't need a StringBuilder
here. Simply using String.format
would do the trick:
String toHexString(byte byteToConvert) {
return String.format("%02x", byteToConvert);
}
Upvotes: 2