Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
293 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...