BAEL-5332-convert-byte-array-and-uuid (#11822)

Co-authored-by: tienvn4 <tienvn4@ghtk.co>
This commit is contained in:
vunamtien 2022-02-16 03:19:44 +07:00 committed by GitHub
parent cc09a52050
commit 864b139aa4
1 changed files with 33 additions and 0 deletions

View File

@ -0,0 +1,33 @@
package com.baeldung.uuid;
import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.UUID;
public class UuidHelper {
public static byte[] convertUUIDToBytes(UUID uuid) {
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
return bb.array();
}
public static UUID convertBytesToUUID(byte[] bytes) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
long high = byteBuffer.getLong();
long low = byteBuffer.getLong();
return new UUID(high, low);
}
public static void main(String[] args) {
UUID uuid = UUID.randomUUID();
System.out.println("Original UUID: " + uuid);
byte[] bytes = convertUUIDToBytes(uuid);
System.out.println("Converted byte array: " + Arrays.toString(bytes));
UUID uuidNew = convertBytesToUUID(bytes);
System.out.println("Converted UUID: " + uuidNew);
}
}