27

Question is How do I convert ByteArray to GUID.

Previously I converted my guid to byte array, and after some transaction I need my guid back from byte array. How do I do that. Although irrelevant but conversion from Guid to byte[] is as below

    public static byte[] getByteArrayFromGuid(String str)
    {
        UUID uuid = UUID.fromString(str);
        ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
        bb.putLong(uuid.getMostSignificantBits());
        bb.putLong(uuid.getLeastSignificantBits());

        return bb.array();
    }

but how do I convert it back??

I tried this method but its not returning me same value

    public static String getGuidFromByteArray(byte[] bytes)
    {
        UUID uuid = UUID.nameUUIDFromBytes(bytes);
        return uuid.toString();
    }

Any help will be appreciated.

Android
  • 3,828
  • 9
  • 46
  • 79

4 Answers4

50

The method nameUUIDFromBytes() converts a name into a UUID. Internally, it applied hashing and some black magic to turn any name (i.e. a string) into a valid UUID.

You must use the new UUID(long, long); constructor instead:

public static String getGuidFromByteArray(byte[] bytes) {
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    long high = bb.getLong();
    long low = bb.getLong();
    UUID uuid = new UUID(high, low);
    return uuid.toString();
}

But since you don't need the UUID object, you can just do a hex dump:

public static String getGuidFromByteArray(byte[] bytes) {
    StringBuilder buffer = new StringBuilder();
    for(int i=0; i<bytes.length; i++) {
        buffer.append(String.format("%02x", bytes[i]));
    }
    return buffer.toString();
}
afathman
  • 5,993
  • 2
  • 20
  • 28
Aaron Digulla
  • 321,842
  • 108
  • 597
  • 820
  • 5
    +1 for Explanation : _Specially_ for Hashing and some _black magic_ :) – akash Jun 25 '14 at 12:52
  • 2
    To be more specific about the 'black magic' (which doesn't really clear up what is really happening), take a look at http://docs.oracle.com/javase/7/docs/api/java/util/UUID.html. Namely, `public UUID(long mostSigBits, long leastSigBits)` can construct any type of UUID you want. It probably can even make invalid UUIDs with types other than 1, 2, 3, or 4 -- but I have not verified this. `nameUUIDFromBytes` will only construct a type 3 UUID. – David J. Aug 10 '14 at 14:55
  • Can confirm @DavidJ.'s comment. I just created a `java.util.UUID` from a ULID from huxi (https://github.com/huxi/sulky/tree/master/sulky-ulid) and `toString()` works fine. NOTE: This is all on JDK11. – The Alchemist Apr 01 '20 at 19:50
10

Try:

public static String getGuidFromByteArray(byte[] bytes) {
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    UUID uuid = new UUID(bb.getLong(), bb.getLong());
    return uuid.toString();
}

Your problem is that UUID.nameUUIDFromBytes(...) only creates type 3 UUIDs, but you want any UUID type.

Harald K
  • 26,314
  • 7
  • 65
  • 111
  • If it is 8 or 16 bytes, it will work. What would happened if it has 4 bytes. I think it will crash ( java.nio.bufferoverflowexception). How can we fix this? – mindus Nov 17 '14 at 12:08
  • 2
    @mindus A UUID is [defined to have 128 bits (16 bytes)](http://en.wikipedia.org/wiki/Universally_unique_identifier#Definition). If you only have the first 32 bits, there's no way to "fix" that. You might want to add input validation and throw an `IllegalArgumentException` if the input is != 16 bytes though. – Harald K Nov 17 '14 at 12:23
2

Try doing same process in reverse:

public static String getGuidFromByteArray(byte[] bytes)
{
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    UUID uuid = new UUID(bb.getLong(), bb.getLong());
    return uuid.toString();
}

For both building and parsing your byte[], you really need to consider the byte order.

Brett Okken
  • 6,210
  • 1
  • 19
  • 25
0

The codec BinaryCodec can encode UUIDs to byte arrays.

// Convert a UUID into an array of bytes
UuidCodec<byte[]> codec = new BinaryCodec();
byte[] bytes = codec.encode(uuid);
// Convert an array of bytes into a UUID
UuidCodec<byte[]> codec = new BinaryCodec();
UUID uuid = codec.decode(bytes);

See: uuid-creator

fabiolimace
  • 972
  • 11
  • 13