繁体   English   中英

将 ByteArray 转换为 UUID java

[英]Convert ByteArray to UUID java

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

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

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

但我如何将其转换回来?

我试过这个方法,但它没有给我返回相同的值

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

任何帮助将不胜感激。

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

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

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 对象,你可以做一个十六进制转储:

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

尝试:

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

您的问题是UUID.nameUUIDFromBytes(...)仅创建类型 3 UUID,但您想要任何 UUID 类型。

尝试反向执行相同的过程:

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

对于构建和解析您的 byte[],您确实需要考虑字节顺序

编解码器BinaryCodec可以将 UUID 编码为字节数组。

// 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);

请参阅: uuid-creator

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM