GUID到ByteArray

Chr*_*row 26 java uuid 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
       };
}
Run Code Online (Sandbox Code Playgroud)

在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;
Run Code Online (Sandbox Code Playgroud)

编辑

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

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

aio*_*obe 64

我会依赖内置的功能:

ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
return bb.array();
Run Code Online (Sandbox Code Playgroud)

或类似的,

ByteArrayOutputStream ba = new ByteArrayOutputStream(16);
DataOutputStream da = new DataOutputStream(ba);
da.writeLong(uuid.getMostSignificantBits());
da.writeLong(uuid.getLeastSignificantBits());
return ba.toByteArray();
Run Code Online (Sandbox Code Playgroud)

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

  • @ AlexandreH.Tremblay这是预料之中的,nameUUIDFromBytes从你传递给它的字节中获取一个哈希值.反序列化上面的格式再读取longs并使用构造函数UUID(long,long) (6认同)

com*_*nad 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();
}
Run Code Online (Sandbox Code Playgroud)