将 ByteArray 转换为 UUID java [英] Convert ByteArray to UUID java

查看:32
本文介绍了将 ByteArray 转换为 UUID java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是如何将 ByteArray 转换为 GUID.

Question is How do I convert ByteArray to GUID.

以前我将我的 guid 转换为字节数组,在一些交易之后我需要从字节数组中取回我的 guid.我怎么做.虽然无关,但从 Guid 到 byte[] 的转换如下

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

任何帮助将不胜感激.

推荐答案

nameUUIDFromBytes() 方法将名称转换为 UUID.在内部,它应用散列和一些黑魔法将任何名称(即字符串)转换为有效的 UUID.

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.

您必须使用 new UUID(long, long); 构造函数:

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

但是由于您不需要 UUID 对象,您可以只进行十六进制转储:

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

这篇关于将 ByteArray 转换为 UUID java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆