GUID到ByteArray

时间:2010-06-06 04:11:43

标签: java guid bytearray uuid

我刚编写此代码以将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 fewer bits

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

4 个答案:

答案 0 :(得分:64)

我会依赖内置功能:

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();

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

答案 1 :(得分:13)

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();
}

答案 2 :(得分:4)

您可以从apache-commons查看UUID。您可能不想使用它,但请检查sources以查看其getRawBytes()方法的实施方式:

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

答案 3 :(得分:0)

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