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生成的类型4 UUID少浪费10位。randomUUID():
public static byte[] getUuidAsBytes(){
int size = 16;
byte[] bytes = new byte[size];
new Random().nextBytes(bytes);
return bytes;
}