Java中UUID编码为22字符的Base64字符串

UUID 是通用唯一识别码(Universally Unique Identifier)的缩写,是一个128比特的数值。UUID是基于当前时间、计数器(counter)和硬件标识(通常为无线网卡的MAC地址)等数据计算生成的,它保证对在同一时空中的所有机器都是唯一的。

Java中UUID类可以方便地获取UUID:

  • fromString:从标准字符串格式中获取UUID;
  • randomUUID:生成一个随机的UUID;
  • nameUUIDFromBytes:根据指定的字节数组获取一个类型3(基于名称)的UUID;
  • getLeastSignificantBits:获取低64bit部分的UUID;
  • getMostSignificantBits:获取高64bit部分的UUID;

常见的UUID是36字符编码的,为了更方便使用且缩写空间占用,可通过Base64编码压缩为22字符(只含字符、数字和下划线、中划线),此种编码可以方便地用于数据库、URL等中。

为了保证只含字符、数字和下划线、中划线,需要使用UrlEncoder:

public class UUIDHelper {
    static final Base64.Encoder _Base64Encoder = Base64.getUrlEncoder().withoutPadding();

    public static byte[] uuid2Bytes(UUID uuid) {
        ByteBuffer buff = ByteBuffer.wrap(new byte[16]);
        buff.putLong(uuid.getMostSignificantBits());
        buff.putLong(uuid.getLeastSignificantBits());
        return buff.array();
    }

    public static String uuid2Base64(UUID uuid) {
        byte[] byUuid = uuid2Bytes(uuid);
        return _Base64Encoder.encodeToString(byUuid);
    }

    public static String getBase64Uuid() {
        UUID uuid = UUID.randomUUID();
        return uuid2Base64(uuid);
    }

   public static UUID base642UUID(String strBase64) {
        byte[] byUuid = Base64.getUrlDecoder().decode(strBase64);
        ByteBuffer buff = ByteBuffer.wrap(byUuid);
        long mostSigBits = buff.getLong();
        long leastSigBits = buff.getLong();
        return new UUID(mostSigBits, leastSigBits);
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值