Search code examples
javanumbershexnumber-formattingnumberformatter

Convert String to Hexadecimal


I want to convert this String "123456" to Hexadecimal String.format("%016x", "123456")

but I got an error

Exception in thread "main" java.util.IllegalFormatConversionException: x != java.lang.String
    at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4302)
    at java.util.Formatter$FormatSpecifier.printInteger(Formatter.java:2793)
    at java.util.Formatter$FormatSpecifier.print(Formatter.java:2747)
    at java.util.Formatter.format(Formatter.java:2520)
    at java.util.Formatter.format(Formatter.java:2455)
    at java.lang.String.format(String.java:2940)
    at Asdfsaf.main(Asdfsaf.java:22)

Solution

  • You cannot convert a string to hexadecimal like that, only a number can be formatted with %016x.

    You can fix this by parsing "123456":

    String.format("%016x", Integer.parseInt("123456"));