问题是我如何将ByteArray转换为guid。
之前我把我的guid转换成了字节数组,在一些交易之后,我需要把我的guid从字节数组中转回来。我应该怎么做。虽然无关紧要,但从guid转换为字节[]的过程是这样的
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的UUIDs,但你想要任何UUID类型。
试试反过来做同样的过程。
public static String getGuidFromByteArray(byte[] bytes)
{
ByteBuffer bb = ByteBuffer.wrap(bytes);
UUID uuid = new UUID(bb.getLong(), bb.getLong());
return uuid.toString();
}
在建立和解析字节[]的过程中,你真的需要考虑到: 字节序.
有一个方法 UuidConverter
从 uuid-creator
可以做到这一点。
UUID uuid = UuidConverter.fromBytes(bytes);
另一种方法则相反。
byte[] bytes = UuidConverter.toBytes(uuid);