1

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"
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
Shaddox27
  • 29
  • 8

1 Answers1

2

You don't need a StringBuilder here. Simply using String.format would do the trick:

String toHexString(byte byteToConvert) {
    return String.format("%02x", byteToConvert);
}
Mureinik
  • 297,002
  • 52
  • 306
  • 350