0

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)
Nuñito Calzada
  • 4,394
  • 47
  • 174
  • 301
  • 2
    Read up on the format patterns (especially about the conversion argument category for "x"). Also, what result would you expect: the hex representation of the byte array created from the string using a specific encoding or the hex representation of the parsed (hint hint) number? – Thomas Jan 24 '18 at 13:13

3 Answers3

5

The value fo x must be an integer.

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

Result:

000000000001e240
3

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"));
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
2

The stack trace stating

x != java.lang.String

States it clearly that String can not be converted to hexadecimal. You should parse it into an integer first before you convert it into hexadecimal.

For parsing you can use

Integer.parseInt(stringVariable);

So your line of code would become:

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

Hope i helped.

Farhan Qasim
  • 990
  • 5
  • 18