-2

I always get an exception

Exception in thread "main" java.util.FormatFlagsConversionMismatchException: Conversion = h, Flags = 0

on this line of code

String.format("%02H", data[i]);

the data array holds char variables.

I want to print these characters in hex format like 09, not only 9.

Kristian Vukusic
  • 3,284
  • 6
  • 30
  • 46

1 Answers1

3

I think you need to use String.format("%02X", (int)data[i]); instead.

Take a look at the answers to Java code To convert byte to Hexadecimal for an expanded discussion on the topic.

Community
  • 1
  • 1
Jason Braucht
  • 2,358
  • 19
  • 31
  • Yes. In fact, the conversion character 'H' implies the hash code of the argument, and the flag '0' is not defined for this conversion. And the '0' flag is not supported for the Character type either. Cast it to an int! – forty-two Apr 22 '12 at 23:23
  • I solved it. Thanks. The char needs to be casted to byte – Kristian Vukusic Apr 22 '12 at 23:26
  • You are right - I'd copy pasted your answer and replaced with the `X` arg but didn't realize you were passing an `int`. Also, be careful casting `char` to `byte`, that's losing a byte. – Jason Braucht Apr 22 '12 at 23:31