Home > Back-end >  How can I pad a hexadecimal digit with 0 in java? [duplicate]
How can I pad a hexadecimal digit with 0 in java? [duplicate]

Time:09-21

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("d", 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("d", Integer.valueOf(orderID)));
        
    }

CodePudding user response:

String.format("x", 255)

with output

00ff

(or use X for uppercases hex digits)

As @user16320675 point, more info about Formatter here.

  • Related