Java 如何减少使用 randomUUID() 生成的 UUID 的长度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20994768/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to reduce length of UUID generated using randomUUID( )
提问by AppleBud
I have a short utility in which I am generating a UUID using randomUUID().
我有一个简短的实用程序,我在其中使用 randomUUID() 生成 UUID。
String uuid = UUID.randomUUID().toString();
However, the uuid generated is too long which is 36 in length.
但是,生成的 uuid 太长,长度为 36。
Is there anyway I can reduce the length of the UUID from 36 to near to 16 or 16 ?
无论如何我可以将 UUID 的长度从 36 减少到接近 16 或 16 吗?
采纳答案by Peter Lawrey
If you don't need it to be unique, you can use any length you like.
如果你不需要它是独一无二的,你可以使用任何你喜欢的长度。
For example, you can do this.
例如,您可以这样做。
Random rand = new Random();
char[] chars = new char[16];
for(int i=0;i<chars.length;i++) {
chars[i] = (char) rand.nextInt(65536);
if (!Character.isValidCodePoint(chars[i]))
i--;
}
String s = new String(chars);
This will give you almost the same degree of randomness but will use every possible character between \u0000
and \ufffd
这将为您提供几乎相同程度的随机性,但将使用\u0000
和\ufffd
If you need printable ASCII characters you can make it as short as you like but the likelihood of uniqueness drops significantly. What can do is use base 36 instead of base 16
如果您需要可打印的 ASCII 字符,您可以让它尽可能短,但唯一性的可能性会显着下降。可以做的是使用 base 36 而不是 base 16
UUID uuid = UUID.randomUUID();
String s = Long.toString(uuid.getMostSignificantBits(), 36) + '-' + Long.toString(uuid.getLeastSignificantBits(), 36);
This will 26 characters on average, at most 27 character.
这将平均 26 个字符,最多 27 个字符。
You can use base64 encoding and reduce it to 22 characters.
您可以使用 base64 编码并将其减少到 22 个字符。
If you use base94 you can get it does to 20 characters.
如果您使用 base94,您可以获得 20 个字符。
If you use the whole range of valid chars fro \u0000 to \ufffd you can reduce it to just 9 characters or 17 bytes.
如果您使用从 \u0000 到 \ufffd 的整个有效字符范围,您可以将其减少到仅 9 个字符或 17 个字节。
If you don't care about Strings you can use 16, 8-bit bytes.
如果您不关心字符串,则可以使用 16 位 8 位字节。
回答by Pritam Panja
Yes,You can create by using this function.
是的,您可以使用此功能创建。
public static String shortUUID() {
UUID uuid = UUID.randomUUID();
long l = ByteBuffer.wrap(uuid.toString().getBytes()).getLong();
return Long.toString(l, Character.MAX_RADIX);
}
回答by Pramin Senapati
String uuid = String.format("%040d", new BigInteger(UUID.randomUUID().toString().replace("-", ""), 16));
String uuid = String.format("%040d", new BigInteger(UUID.randomUUID().toString().replace("-", ""), 16));
String uuid16digits = uuid.substring(uuid.length() - 16);
字符串 uuid16digits = uuid.substring(uuid.length() - 16);
This will return the last 16 digits of actual uuid.
这将返回实际 uuid 的最后 16 位数字。