How to convert an int to hex with leading zeros in Java?

Morgan G :

I need to convert the numbers 1 to 255 (address) into hex values from 01 to FE (hexAddress).

There must be a leading 0 for values from 01 to 0F, the letters must be uppercase, and there cannot be a 0x prepended to the hex value.

Edit: This question is not a duplicate. The question that it is cited as a duplicate of has an accepted answer that does not work for this situation, nor does it fully explain how it works.

Morgan G :
String hexAddress = String.format("%1$02X",address);

%1 means these flags are for the first argument. In this case, there is only one argument.

$ separates the argument index from the flags

0 is a flag that means pad the result with leading zeros up to the specified bit width.

2 is the bit width

X means convert the number to hex, and use uppercase letters. x would convert to hex and use lowercase letters.

You can read more about the different possible arguments by examining the Java Formatter class.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=442967&siteId=1