java.util.UUID.randomUUID().toString() 长度

java.util.UUID.randomUUID().toString() length

java.util.UUID.randomUUID().toString() 长度是否总是等于 36?

我找不到相关信息。 Here据说只有以下内容:

public static UUID randomUUID() Static factory to retrieve a type 4 (pseudo randomly generated) UUID. The UUID is generated using a cryptographically strong pseudo random number generator. Returns: A randomly generated UUID

type 4 什么也没告诉我。我不知道这种情况下类型4是什么意思。

Does java.util.UUID.randomUUID().toString() length always equal to 36?

是的!!是的。

A UUID 实际上是一个 128 位的值(2 长)。要将 128 位表示为十六进制字符串,将有 128/4=32 字符(每个字符长 4 位)。在字符串格式中,它还包含 4 (-),这就是长度为 36 的原因。

示例:54947df8-0e9e-4471-a2f9-9af509fb5889

32 个十六进制字符 + 4 个连字符字符 = 36 个字符。所以长度将始终相同。


更新:

I do not know what type 4 means in the case.?

仅供参考:有几种生成 UUID 的方法。这里类型 4 表示此 uuid 是使用随机数或伪随机数生成的。来自 wiki - Universally_unique_identifier#Versions:

Versions

For both variants 1 and 2, five "versions" are defined in the standards, and each version may be more appropriate than the others in specific use cases. Version is indicated by the M in the string representation.

Version 1 UUIDs are generated from a time and a node id (usually the MAC address);

version 2 UUIDs are generated from an identifier (usually a group or user id), time, and a node id;

versions 3 and 5 produce deterministic UUIDs generated by hashing a namespace identifier and name;

and version 4 UUIDs are generated using a random or pseudo-random number.

您可以使用 base64 将 UUIDv4 16 字节二进制转换为 24 字节 ascii,而不是编码为 ascii-hex(32 字节)

对于像我这样在阅读 javadoc 之前就开始谷歌搜索的人,这里是 javadoc ;)

UUID.toString

对于那些不知道如何阅读语法树的人,请从下到上阅读。
一个 hexDigit 是一个 char
一个 hexOctet 是 2 个 hexDigits = 2chars
一个 node 是 6 * hexOctet = 6 * 2hexdigit = 6*2 chars = 12chars
一个 variant_and_sequence 是 2 * hexOctet = 2 * 2hexdigit = 2*2 chars = 4chars
a time_high_and_version 是 2 * hexOctet = 2 * 2hexdigit = 2*2 chars = 4chars
a time_mid 是 2 * hexOctet = 2 * 2hexdigit = 2*2 chars = 4chars
a time_low 是 4 * hexOctet = 4* 2hexdigit = 4*2 chars = 8chars
最后,UUID 是 < time_low > "-" < time_mid > "-" < time_high_and_version > "-" < variant_and_sequence > "-"<节点>

= 8 个字符 + 1 个字符 + 4 个字符 + 1 个字符 + 4 个字符 + 1 个字符 + 4 个字符 + 1 个字符 + 12 个字符

= 36 个字符! 128 位数据 + 4 个连字符,如前所述

The UUID string representation is as described by this BNF: 

 UUID                   = <time_low> "-" <time_mid> "-"
                          <time_high_and_version> "-"
                          <variant_and_sequence> "-"
                          <node>
 time_low               = 4*<hexOctet>
 time_mid               = 2*<hexOctet>
 time_high_and_version  = 2*<hexOctet>
 variant_and_sequence   = 2*<hexOctet>
 node                   = 6*<hexOctet>
 hexOctet               = <hexDigit><hexDigit>
 hexDigit               =
       "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9"
       | "a" | "b" | "c" | "d" | "e" | "f"
       | "A" | "B" | "C" | "D" | "E" | "F"