I just wrote this code to convert a GUID into a byte array. Can anyone shoot any holes in it or suggest something better?
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
};
}
In C++, I remember being able to do this, but I guess theres no way to do it in Java with the memory management and all?:
UUID uuid = UUID.randomUUID();
long[] longArray = new long[2];
longArray[0] = uuid.getMostSignificantBits();
longArray[1] = uuid.getLeastSignificantBits();
byte[] byteArray = (byte[])longArray;
return byteArray;
Edit
If you want to generate a completely random UUID as bytes that does not conform to any of the official types, this will work and wastes 10 fewer bits than type 4 UUIDs generated by UUID.randomUUID():
public static byte[] getUuidAsBytes(){
int size = 16;
byte[] bytes = new byte[size];
new Random().nextBytes(bytes);
return bytes;
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…