user3249763
user3249763

Reputation: 127

Formatting a hex

I have a integer, which I am trying to convert to a hex, and then pad with leading 0s so that the length of the string is 16 characters Below is my code

long longdpid = Long.parseLong(dataPathID);
String stringhexdpid = Long.toHexString(longdpid);
String.format("%016x", stringhexdpid);

and I am getting the following error:

Exception in thread "POLLtimer" java.util.IllegalFormatConversionException: x != java.lang.String
at java.util.Formatter$FormatSpecifier.failConversion(Formatter.java:4045) 

Could someone explain where my mistake is?

Upvotes: 0

Views: 2378

Answers (4)

user2737926
user2737926

Reputation: 97

In String.format(), Just try longdpid instead of stringhexdpid. This should work.

Upvotes: 0

dkatzel
dkatzel

Reputation: 31648

%x takes an integer not a String

String.format("%016x", longdpid);

should work

Upvotes: 1

Jim Garrison
Jim Garrison

Reputation: 86774

String stringhexdpid = Long.toHexString(longdpid);

After you do that you have a String

However in

String.format("%016x", stringhexdpid);

You are telling it to expect a long. What you want is '%016s', but that does not work since %s doesn't do left-padding.

To solve the problem, just do

String.format("%016x", longdpid);

Upvotes: 0

Jonathan
Jonathan

Reputation: 91

Your mistake is that String.format will do the conversion to hex for you. You don't need to call Long.toHexString() yourself. The format code x you are using requires an integer, not a string. Read more at http://docs.oracle.com/javase/7/docs/api/java/util/Formatter.html#syntax

Upvotes: 1

Related Questions