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.
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.