关于字符串:java.util.UUID.randomUUID()。toString()的长度

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

java.util.UUID.randomUUID()。toString()的长度是否始终等于36?

我找不到有关的信息。 这里只说以下几点:

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?

是!!它是。

UUID实际上是一个128位值(2个长整数)。为了将128位表示为十六进制字符串,将有一个128/4=32 char(每个char为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是一个字符
hexOctet是2 hexDigits = 2chars
一个节点是6 * hexOctet = 6 * 2hexdigit = 6 * 2个字符= 12个字符
variant_and_sequence是2 * hexOctet = 2 * 2hexdigit = 2 * 2个字符= 4个字符
time_high_and_version为2 * hexOctet = 2 * 2hexdigit = 2 * 2个字符= 4个字符
time_mid为2 * hexOctet = 2 * 2hexdigit = 2 * 2个字符= 4个字符
time_low是4 * hexOctet = 4 * 2hexdigit = 4 * 2个字符= 8个字符
最后,UUID为"-" "-" "-" "-" <节点>

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
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"