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"
user7294900
  • 52,490
  • 20
  • 92
  • 189
Shaddox27
  • 29
  • 6

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
  • 277,661
  • 50
  • 283
  • 320