Javaでバイト配列とUUIDの間で変換
1. 概要
この短いチュートリアルでは、Javaでバイト配列とUUIDの間で変換する方法を説明します。
2. UUIDをバイト配列に変換します
UUIDをプレーンJavaのバイト配列に簡単に変換できます。
public static byte[] convertUUIDToBytes(UUID uuid) {
ByteBuffer bb = ByteBuffer.wrap(new byte[16]);
bb.putLong(uuid.getMostSignificantBits());
bb.putLong(uuid.getLeastSignificantBits());
return bb.array();
}
3. バイト配列をUUIDに変換します
バイト配列をUUIDに変換するのも同じくらい簡単です。
public static UUID convertBytesToUUID(byte[] bytes) {
ByteBuffer byteBuffer = ByteBuffer.wrap(bytes);
long high = byteBuffer.getLong();
long low = byteBuffer.getLong();
return new UUID(high, low);
}
4. メソッドをテストする
メソッドをテストしてみましょう。
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);
結果は次のようになります。
Original UUID: bd9c7f32-8010-4cfe-97c0-82371e3276fa
Converted byte array: [-67, -100, 127, 50, -128, 16, 76, -2, -105, -64, -126, 55, 30, 50, 118, -6]
Converted UUID: bd9c7f32-8010-4cfe-97c0-82371e3276fa
5. 結論
このクイックチュートリアルでは、Javaでバイト配列とUUIDの間で変換する方法を学習しました。
いつものように、この記事のサンプルコードは、GitHubのにあります。