将ByteArray转换为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对象,因此您只需执行hex转储:
public static String getGuidFromByteArray(byte[] bytes) { StringBuilder buffer = new StringBuilder(); for(int i=0; i
尝试:
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 [],您确实需要考虑字节顺序 。