How to generate unique number of 12 digits?

前端 未结 4 1459
误落风尘
误落风尘 2021-01-03 17:08

I\'m working on an app that sends raw data to zebra printer and print out barcodes. And since every item has its own unique barcode, I need to define a variable that automat

相关标签:
4条回答
  • 2021-01-03 17:38

    Start with a twelve digit number, ie: 111111111111

    to get your new 'random' unique number take the previous number and add 1.

    although not random, it will guarantee uniqueness.

    0 讨论(0)
  • 2021-01-03 17:40

    You can simply use:

    var temp = Guid.NewGuid().ToString().Replace("-", string.Empty);
    var barcode = Regex.Replace(temp,"[a-zA-Z]", string.Empty).Substring(0, 12);
    
    0 讨论(0)
  • 2021-01-03 17:42

    How many times do you generate a new barcode per day, hour, minute?

    You could use a technique like the auto versioning of Visual Studio works.

    • Count the number of days from some specific date (e.g. 1.1.2000)
      • padded with 0 to five places.
    • Concat the seconds elapsed till midnight
      • padded also with zero to five places.
    • Fill up the last two numbers with a static counter in your App that just wrap around at 99.

    Example

    public static class UniqueId
    {
        static private int _InternalCounter = 0;
    
        static public string Get()
        {
            var now = DateTime.Now;
    
            var days = (int)(now - new DateTime(2000, 1, 1)).TotalDays;
            var seconds = (int)(now - DateTime.Today).TotalSeconds;
    
            var counter = _InternalCounter++ % 100;
    
            return days.ToString("00000") + seconds.ToString("00000") + counter.ToString("00");
        }
    

    With this approach you'll get an overflow at the 15. October 2273, but i think this can be solved by your follower. ;-)

    If you need to create more than hundred unique IDs per second you can change the last two line into:

    var counter = _InternalCounter++ % 1000;
    return days.ToString("0000") + seconds.ToString("00000") + counter.ToString("000");
    

    Now you'll have thousand unique IDs per second, but the days will already overflow at 18. May 2027. If this is too short, you can get additional ten years if you set the start date to 2010 by this line:

    var days = (int)(now - new DateTime(2010, 1, 1)).TotalDays;
    
    0 讨论(0)
  • 2021-01-03 18:03

    Using an RNG and a hash do:

    10 - stream out 12 digits
    20 - check if value is in hash
    30 - if it's goto 40 else goto 10
    40 - push value into hash
    50 - return new 12 digit number
    60 - goto 10

    0 讨论(0)
提交回复
热议问题