【问题标题】:How can I convert a UUID to base64?如何将 UUID 转换为 base64?
【发布时间】:2015-01-24 20:00:54
【问题描述】:

我想输入UUID 并以Base64 编码格式输出,但是考虑到Base64 上的输入方法和UUID 上的输出,如何实现这一点似乎并不明显。

update 虽然不是我的用例的明确要求,但很高兴知道所使用的方法是否使用 UUID 的原始 UUID(UUID 实际是 128 位),如标准的十六进制编码。

【问题讨论】:

标签: java encoding base64 uuid


【解决方案1】:

首先,将您的 UUID 转换为字节缓冲区以供 Base64 encoder 使用:

ByteBuffer uuidBytes = ByteBuffer.wrap(new byte[16]);
uuidBytes.putLong(uuid.getMostSignificantBits());
uuidBytes.putLong(uuid.getLeastSignificantBits());

然后使用编码器对其进行编码:

byte[] encoded = encoder.encode(uuidBytes);

或者,您可以像这样获得 Base64 编码的字符串:

String encoded = encoder.encodeToString(uuidBytes);

【讨论】:

  • 我从来没有想过要先toString,但尽管对我没有明确要求,但这实际上与对 UUID 的原始字节进行 Base64 编码相同吗?
  • @xenoterracide 不,不一样;我已经用使用原始字节的版本更新了我的答案。
【解决方案2】:

您可以使用来自 apache commons 编解码器的 Base64。 https://commons.apache.org/proper/commons-codec/apidocs/org/apache/commons/codec/binary/Base64.html

import java.util.UUID;
import org.apache.commons.codec.binary.Base64;

public class Test {

    public static void main(String[] args) {
        String uid = UUID.randomUUID().toString();
        System.out.println(uid);
        byte[] b = Base64.encodeBase64(uid.getBytes());
        System.out.println(new String(b));
    }

}

【讨论】:

  • 我没有否决你的答案,而是给你一个提示为什么人们可能不喜欢它:你的方法对已经编码的字节(十六进制加上一些分隔符,然后是 Unicode)的字符串表示Base64 中的 UUID,而不是 UUID 本身的字节。另请注意,从 Java 1.8 开始,有 Base64 support in the standard library itself,因此不再需要使用外部库。
  • 感谢@5gon12eder 的建设性评论 它让我们其他人的事情变得更清楚,也让环境变得更好(:
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-07-27
  • 1970-01-01
  • 2013-03-29
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
相关资源
最近更新 更多