问题是如何将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类型.