views:

259

answers:

2
+1  Q: 

GUID to ByteArray

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;
}
+3  A: 

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!)

aioobe
+1  A: 

You can checkUUID from apache-commons. You may not want to use it, but check the sources to see how it its getRawBytes() method is implemented.

Bozho