zoukankan      html  css  js  c++  java
  • 如何生成比较短的“唯一”字符串

    原文:Generate unique strings and numbers in C#

    Generate unique strings and numbers in C#
    By Mads Kristensen

    The System.Guid is used whenever we need to generate a unique key, but it is very long. That's in many cases not an issue, but in a web scenario where it is part of the URL we need to use its string representation which is 36 characters long. It clutters up the URL and is just basically ugly.

    It is not possible to shorten it without loosing some of the uniqueness of the GUID, but we can come a long way if we can accept a 16 character string instead.

    We can change the standard GUID string representation:

    21726045-e8f7-4b09-abd8-4bcc926e9e28

    Into a shorter string:

    3c4ebc5f5f2c4edc

    The following method creates the shorter string and it is actually very unique. An iteration of 10 million didn.t create a duplicate. It uses the uniqueness of a GUID to create the string.

    private string GenerateId()
    {
     long i = 1;
     foreach (byte b in Guid.NewGuid().ToByteArray())
     {
      i *= ((int)b + 1);
     }
     return string.Format("{0:x}", i - DateTime.Now.Ticks);
    }

    If you instead want numbers instead of a string, you can do that to but then you need to go up to 19 characters. The following method converts a GUID to an Int64.

    private long GenerateId()
    {
     byte[] buffer = Guid.NewGuid().ToByteArray();
     return BitConverter.ToInt64(buffer, 0);
    }

    The standard GUID is still the best way to ensure the uniqueness even though it isn't 100% unique

  • 相关阅读:
    bzoj1066: [SCOI2007]蜥蜴
    bzoj3504: [Cqoi2014]危桥
    bzoj2756: [SCOI2012]奇怪的游戏
    bzoj1570: [JSOI2008]Blue Mary的旅行
    Ultra-QuickSort
    Bin Packing
    Watering Grass
    区间覆盖
    抄书 Copying Books UVa 714
    分馅饼 Pie
  • 原文地址:https://www.cnblogs.com/headchen/p/839851.html
Copyright © 2011-2022 走看看