GUID 到 ByteArray

2022-09-01 13:38:03

我刚刚编写了此代码以将 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生成的类型4 UUID少浪费10位。randomUUID():

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

答案 1

我会依靠内置功能:

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

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


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