0

I am trying to convert a String to it's hex representation. I have the following (test) input �¾��Hello World!

The correct hex representation should be: 00 BE 00 00 48 65 6C 6C 6F 20 57 6F 72 6C 64 21

I am trying to format the String with String.format("%x", new BigInteger(toConvert.getBytes("ISO-8859-1"))).split("(?<=\\G.{2})");

But this format operation ignores the first character (if it is a hex-null) and leads to BE 00 00 48 65 6C 6C 6F 20 57 6F 72 6C 64 21

I have already played around a little bit with the parts around the "%x" but nothing helped.

But I am sure, that you can help me :)

smsnheck
  • 1,563
  • 3
  • 21
  • 33

1 Answers1

0

To format with leading zeroes, specify the width of the formatted hex value, and request leading zeroes.

E.g. if result is 6 bytes, instead of format "%x", use format "%012x".

For your code, do this: "%0" + toConvert.length() * 2 + "x"

Andreas
  • 154,647
  • 11
  • 152
  • 247