Convert ByteArray to UUID java

自作多情 提交于 2019-12-18 02:40:32

问题


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.


回答1:


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();
}



回答2:


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.




回答3:


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.




回答4:


There's a method in UuidUtil from uuid-creator that does that.

UUID uuid = UuidUtil.fromBytesToUuid(bytes);

Another method does the reverse.

byte[] bytes = UuidUtil.fromUuidToBytes(uuid);

https://github.com/f4b6a3/uuid-creator



来源:https://stackoverflow.com/questions/24408984/convert-bytearray-to-uuid-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!