JKh*_*ang 18
GUID的长度为128位(16字节),因此如果要创建短GUID,则必须更改GUID的编码.
例如,您可以使用base64或ASCII85.
/// <summary>
/// Creates a GUID which is guaranteed not to equal the empty GUID
/// </summary>
/// <returns>A 24 character long string</returns>
public static string CreateGuid()
{
Guid guid = Guid.Empty;
while (Guid.Empty == guid)
{
guid = Guid.NewGuid();
}
// Uses base64 encoding the guid.(Or ASCII85 encoded)
// But not recommend using Hex, as it is less efficient.
return Convert.ToBase64String(guid.ToByteArray());
}
Run Code Online (Sandbox Code Playgroud)
Chr*_*cht 13
杰夫阿特伍德在他的博客上有一篇文章如何在不丢失信息的情况下将GUID缩短为20个字符:
编码恐怖:装备我们的ASCII装甲
K. *_*R. 5
一年内独一无二,明显'随机'
string UniqueID()
{
var t = DateTime.UtcNow;
long dgit = t.Millisecond * 1000000000L +
t.DayOfYear * 1000000L +
t.Hour * 10000L +
t.Minute * 100L +
t.Second;
return Convert.ToBase64String(BitConverter.GetBytes(dgit).Take(5).ToArray()).TrimEnd('=');
}
Run Code Online (Sandbox Code Playgroud)
这是一个可定制的字符集
string UniqueID(string CharList = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
{
var t = DateTime.UtcNow;
char[] charArray = CharList.ToCharArray();
var result = new Stack<char>();
var length = charArray.Length;
long dgit = 1000000000000L +
t.Millisecond * 1000000000L +
t.DayOfYear * 1000000L +
t.Hour * 10000L +
t.Minute * 100L +
t.Second;
while (dgit != 0)
{
result.Push(charArray[dgit % length]);
dgit /= length;
}
return new string(result.ToArray());
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27126 次 |
| 最近记录: |