I need a way to print a number as hex, as a zero-padded string of width N, where N is selectable at runtime.
This doesn't work:
System.out.println(String.format("%*x", 4, 0x123))
because evidently Java doesn't support the C-style use of %* f开发者_运维问答or runtime-selectable width format strings.
Any suggestions for an alternative?
int width = 4;
String format = "%" + width + "x";
System.out.println(String.format(format, 0x123));
:wrysmile:
@fd also with printf
int width = 4;
String format = "%" + width + "x";
System.out.printf(format, 0x123);
System.out.printf("%4x", 0x123);
Use an appropriate NumberFormat.
EDIT
This is plain wrong..
精彩评论