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 automatically generates unique number of 12 digits long.
see example:
printBar prnt = new printBar("123456789012");
Is there anyway to define a double variable and pass it to a function that return uniqely 12 digits number and pass it over again to the printBar class?. But how to make sure everytime you access it returns a unique value?.
I also开发者_如何学Python thought of another way, since am using MS Access db, I can create a column of AutoNumber datatype and assign it to Random, but you don't get the exact 12 digits required, sometimes it generates a value of 10 digits sometimes more or less.
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.
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;
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
精彩评论