将ByteArray转换为UUID java [英] Convert ByteArray to 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();
}
但如何将其转换回来?
我试过这个方法,但它没有给我返回相同的值
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.
推荐答案
方法 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.
您必须使用新的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对象,你可以做一个十六进制转储:
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屋!