拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 Java中字节数组和UUID之间的转换

Java中字节数组和UUID之间的转换

白鹭 - 2022-03-07 2237 0 2

一、概述

在这个简短的教程中,我们将看到如何在Java 中在字节数组和UUID之间进行转换

2.将字节数组转换为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);
 }

3.将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();
 }

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


标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *