Convert Between Byte Array and UUID in Java – 在Java中转换字节数组和UUID

最后修改: 2022年 2月 22日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this short tutorial, we’ll see how to convert between a byte array and UUID in Java.

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

2. Convert UUID to Byte Array

2.将UID转换为字节数组

We can easily convert a UUID to a byte array in plain Java:

我们可以在普通的Java中轻松地将UID转换为字节数组。

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. Convert Byte Array to UUID

3.将字节数组转换为UID

Converting a byte array to UUID is just as simple:

将一个字节数组转换为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. Test Our Methods

4.测试我们的方法

Let’s test our methods:

让我们测试一下我们的方法。

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

The result will look something like:

其结果将看起来像这样。

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. Conclusion

5.总结

In this quick tutorial, we’ve learned how to convert between a byte array and UUID in Java.

在这个快速教程中,我们已经学会了如何在Java中进行字节数组和UUID之间的转换。

As always, the example code from this article can be found over on GitHub.

一如既往,本文中的示例代码可以在GitHub上找到over