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;
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; }
A GUID is a 128-bit integer (16 bytes) value. That means that there are more than 300, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000, 000 different values. A big number, isn't it? It is virtually impossible to have duplicates, so it is safe to use.
A GUID is a 128-bit integer (16 bytes) that can be used across all computers and networks wherever a unique identifier is required.
GUID stands for Global Unique Identifier. A GUID is a 128-bit integer (16 bytes) that you can use across all computers and networks wherever a unique identifier is required.
GUID is a 16 byte binary SQL Server data type that is globally unique across tables, databases, and servers. The term GUID stands for Globally Unique Identifier and it is used interchangeably with UNIQUEIDENTIFIER.
I would rely on built in functionality:
ByteBuffer bb = ByteBuffer.wrap(new byte[16]); bb.putLong(uuid.getMostSignificantBits()); bb.putLong(uuid.getLeastSignificantBits()); return bb.array();
or something like,
ByteArrayOutputStream ba = new ByteArrayOutputStream(16); DataOutputStream da = new DataOutputStream(ba); da.writeLong(uuid.getMostSignificantBits()); da.writeLong(uuid.getLeastSignificantBits()); return ba.toByteArray();
(Note, untested code!)
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With