GUID到ByteArray

我刚刚编写了这段代码,将GUID转换为字节数组。 任何人都可以拍摄任何洞或建议更好的东西?

public static byte[] getGuidAsByteArray(){ UUID uuid = UUID.randomUUID(); long longOne = uuid.getMostSignificantBits(); long longTwo = uuid.getLeastSignificantBits(); return new byte[] { (byte)(longOne >>> 56), (byte)(longOne >>> 48), (byte)(longOne >>> 40), (byte)(longOne >>> 32), (byte)(longOne >>> 24), (byte)(longOne >>> 16), (byte)(longOne >>> 8), (byte) longOne, (byte)(longTwo >>> 56), (byte)(longTwo >>> 48), (byte)(longTwo >>> 40), (byte)(longTwo >>> 32), (byte)(longTwo >>> 24), (byte)(longTwo >>> 16), (byte)(longTwo >>> 8), (byte) longTwo }; } 

在C ++中,我记得能够做到这一点,但我想在内存管理方面没有办法在Java中做到这一点吗?:

  UUID uuid = UUID.randomUUID(); long[] longArray = new long[2]; longArray[0] = uuid.getMostSignificantBits(); longArray[1] = uuid.getLeastSignificantBits(); byte[] byteArray = (byte[])longArray; return byteArray; 

编辑

如果要生成完全随机的UUID作为不符合任何官方类型的字节,这将比UUID.randomUUID()生成的类型4 UUID 少10个比特 :

  public static byte[] getUuidAsBytes(){ int size = 16; byte[] bytes = new byte[size]; new Random().nextBytes(bytes); return bytes; } 

我会依赖内置的function:

 ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); return bb.array(); 

或类似的,

 ByteArrayOutputStream ba = new ByteArrayOutputStream(16); DataOutputStream da = new DataOutputStream(ba); da.writeLong(uuid.getMostSignificantBits()); da.writeLong(uuid.getLeastSignificantBits()); return ba.toByteArray(); 

(注意,未经测试的代码!)

 public static byte[] newUUID() { UUID uuid = UUID.randomUUID(); long hi = uuid.getMostSignificantBits(); long lo = uuid.getLeastSignificantBits(); return ByteBuffer.allocate(16).putLong(hi).putLong(lo).array(); } 

您可以从apache-commons检查UUID 。 您可能不想使用它,但检查源以查看其getRawBytes()方法是如何实现的:

 public UUID(long mostSignificant, long leastSignificant) { rawBytes = Bytes.append(Bytes.toBytes(mostSignificant), Bytes.toBytes(leastSignificant)); } 

你可以看看Apache Commons Lang3 Conversion.uuidToByteArray(…) 。 相反,请查看Conversion.byteArrayToUuid(…)以转换回UUID。