Skip to content

Commit acc3611

Browse files
vunamtientienvn4
andauthored
BAEL-5332-convert-byte-array-and-uuid (eugenp#11822)
Co-authored-by: tienvn4 <[email protected]>
1 parent ddb7b9e commit acc3611

1 file changed

Lines changed: 33 additions & 0 deletions

File tree

  • core-java-modules/core-java-8-2/src/main/java/com/baeldung/uuid
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
package com.baeldung.uuid;
2+
3+
import java.nio.ByteBuffer;
4+
import java.util.Arrays;
5+
import java.util.UUID;
6+
7+
public class UuidHelper {
8+
9+
public static byte[] convertUUIDToBytes(UUID uuid) {
10+
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
11+
bb.putLong(uuid.getMostSignificantBits());
12+
bb.putLong(uuid.getLeastSignificantBits());
13+
return bb.array();
14+
}
15+
16+
public static UUID convertBytesToUUID(byte[] bytes) {
17+
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
18+
long high = byteBuffer.getLong();
19+
long low = byteBuffer.getLong();
20+
return new UUID(high, low);
21+
}
22+
23+
public static void main(String[] args) {
24+
UUID uuid = UUID.randomUUID();
25+
System.out.println("Original UUID: " + uuid);
26+
27+
byte[] bytes = convertUUIDToBytes(uuid);
28+
System.out.println("Converted byte array: " + Arrays.toString(bytes));
29+
30+
UUID uuidNew = convertBytesToUUID(bytes);
31+
System.out.println("Converted UUID: " + uuidNew);
32+
}
33+
}

0 commit comments

Comments
 (0)