0

I'm trying to pad a hexadecimal digit with 0's in the beginning so that the length of it is always 4. For example, the FF is going to be padded as 00FF. I have tried to use String.format("%04d", number) but it didn't work as my hexadecimal digit is actually a string. I have also tried using StringUtils.leftPad() but for some reason, IntelliJ couldn't detect it.

Please note my count is going to change, but I haven't represented it here as I'm yet to implement it. This is my sample code. Thanks.

    public static void main(String[] args) {
        int count = 0;
        String orderID = Integer.toHexString(count).toUpperCase();
        System.out.println(String.format("%04d", Integer.valueOf(orderID)));
        
    }
Ava-123
  • 3
  • 3
  • `String orderID = Integer.toHexString(count).toUpperCase(); String.format("%04d", Integer.valueOf(orderID))` ... What? Just get rid of the first line and pass in `count` to `String.format`. There is no reason to go from `int` to `String` back to `int` just to format another `String`. – tkausl Sep 19 '21 at 16:48
  • Use `format` directly to format the integer to hex (use `X` instead of `d` in the format string). – Slaw Sep 19 '21 at 16:48
  • Possibly related: [Integer to two digits hex in Java](https://stackoverflow.com/q/8689526) -> `System.out.printf("%04X", count);`. You can add `%n` at the end of format to generate line separator similarly to what `println` does: `System.out.printf("%04X%n", count);` – Pshemo Sep 19 '21 at 16:53
  • @tkausl, that was a method that I tried, of course, it isn't correct, and in the end, I need a string, not an int. – Ava-123 Sep 19 '21 at 17:09

1 Answers1

2
String.format("%04x", 255)

with output

00ff

(or use X for uppercases hex digits)

As @user16320675 point, more info about Formatter here.

josejuan
  • 9,338
  • 24
  • 31