2

Is there any utility method available to convert plain string to UUID formatted string?

For example:

Plain String: f424376fe38e496eb77d7841d915b074

UUID formatted String: f424376f-e38e-496e-b77d-7841d915b074

I just wanted to convert to UUID format without using any java logic, hence looking for predefined utility available in java.lang, java.util or Apache, etc packages.

mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
Paramesh Korrakuti
  • 1,997
  • 4
  • 27
  • 39

1 Answers1

18

You can simply use String.format in the following way:

String plain = "f424376fe38e496eb77d7841d915b074";
String uuid = String.format("%1$-%2$-%3$-%4$", plain.substring(0,7), plain.substring(7,11), plain.substring(11,15), plain.substring(15,20));

Or with more library methods using Apache Commons Codec (org.apache.commons.codec.binary.Hex class) and JDK (java.util.UUID class):

byte[] data = Hex.decodeHex("f424376fe38e496eb77d7841d915b074".toCharArray());
String uuid = new UUID(ByteBuffer.wrap(data, 0, 8).getLong(), ByteBuffer.wrap(data, 8, 8).getLong()).toString();
Vladimír Schäfer
  • 15,375
  • 2
  • 51
  • 71