• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 592
  • Last Modified:

Generate Int64 random numbers

How can I generate a 16 digits Random numbers?

Using the .Net Random method can only generate 9 digits:

long n = new Random().Next(100000000, 999999999);


Any help would be greatly appreciated.


Thanks.
0
JimiJ13
Asked:
JimiJ13
  • 6
  • 4
  • 3
  • +1
3 Solutions
 
PawełI Design & Develop SoftwareCommented:
create a byte array of random values, then convert it to a int64

 Random rnd = new Random();
            var buffer = new byte[sizeof(Int64)];
            rnd.NextBytes(buffer);
            var num = BitConverter.ToInt64(buffer, 0);
            Console.WriteLine(num);
0
 
sarabandeCommented:
or

Random rnd = new Random();
Int64 i64 = rnd.Next(1000000, 9999999);
i64 = (i64*1000000)+rnd.Next(0, 999999999);

Open in new window


Sara
0
 
Fernando SotoRetiredCommented:
Hi  JimiJ13;

This is one way that Microsoft show how to do what you want.
From Microsoft Documentation:
The overloads of the Next method return 32-bit integers. However, in some cases, you might want to work with 64-bit integers. You can do this as follows:

1. Call the NextDouble method to retrieve a double-precision floating point value.
2. Multiply that value by Int64.MaxValue.

The following example uses this technique to generate 20 million random long integers and categorizes them in 10 equal groups. It then evaluates the distribution of the random numbers by counting the number in each group from 0 to Int64.MaxValue. As the output from the example shows, the numbers are distributed more or less equally through the range of a long integer.

const long ONE_TENTH = 922337203685477581;

Random rnd = new Random();
long number;
int[] count = new int[10];

// Generate 20 million long integers.
for (int ctr = 1; ctr <= 20000000; ctr++) {
 number = (long) (rnd.NextDouble() * Int64.MaxValue);
 // Categorize random numbers.
 count[(int) (number / ONE_TENTH)]++;
}
// Display breakdown by range.
Console.WriteLine("{0,28} {1,32}   {2,7}\n", "Range", "Count", "Pct.");
for (int ctr = 0; ctr <= 9; ctr++)
 Console.WriteLine("{0,25:N0}-{1,25:N0}  {2,8:N0}   {3,7:P2}", ctr * ONE_TENTH,
                    ctr < 9 ? ctr * ONE_TENTH + ONE_TENTH - 1 : Int64.MaxValue,
                    count[ctr], count[ctr]/20000000.0);
                              
The results of the above code
// The example displays output like the following:
//                           Range                            Count      Pct.
//    
//                            0-  922,337,203,685,477,580  1,996,148    9.98 %
//      922,337,203,685,477,581-1,844,674,407,370,955,161  2,000,293   10.00 %
//    1,844,674,407,370,955,162-2,767,011,611,056,432,742  2,000,094   10.00 %
//    2,767,011,611,056,432,743-3,689,348,814,741,910,323  2,000,159   10.00 %
//    3,689,348,814,741,910,324-4,611,686,018,427,387,904  1,999,552   10.00 %
//    4,611,686,018,427,387,905-5,534,023,222,112,865,485  1,998,248    9.99 %
//    5,534,023,222,112,865,486-6,456,360,425,798,343,066  2,000,696   10.00 %
//    6,456,360,425,798,343,067-7,378,697,629,483,820,647  2,001,637   10.01 %
//    7,378,697,629,483,820,648-8,301,034,833,169,298,228  2,002,870   10.01 %
//    8,301,034,833,169,298,229-9,223,372,036,854,775,807  2,000,303   10.00 %            
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
JimiJ13I T ConsultantAuthor Commented:
@Paweł & @sarabande

Both of your suggestion works but how can I fix the result to 16 digits always?


Thanks.
0
 
JimiJ13I T ConsultantAuthor Commented:
@Fernando Soto

Thanks for your suggestion. I want only to get one Random Number at a time.

Thanks.
0
 
Fernando SotoRetiredCommented:
Hi JimiJ13;

How about something liken this.
const ulong minLong = 1000000000000000;
const ulong maxLong = 9999999999999999;

Random rnd = new Random();
ulong number;

do
{
    number = (ulong)(rnd.NextDouble() * maxLong);
}  while (!(number >= minLong && number <= maxLong));

Open in new window

0
 
PawełI Design & Develop SoftwareCommented:
Depends on how random you need your number to be, you could trim what is produced by either subtracting the appropriate value or by just pulling digits off, but I'm curious as to why you need a 16 digit number? Because if you are building unique keys you should use a GUID instead.
Something like var I'd = Guid.NewGuid();

It won't be a number, well sort of it'll be a hex value but very unique  almost certainly  unique, much more unique then any of the solutions provided
0
 
JimiJ13I T ConsultantAuthor Commented:
@Fernando Soto

It works. However, is this not slower compare to other suggestion?


Thanks.
0
 
JimiJ13I T ConsultantAuthor Commented:
@Paweł,

Your suggestion using GUID is really good if there is no existing BigInt data of about a million rows related to other tables and being used for 2-3 specific transactions.  We are doing now a new external transaction page and we need distinguish this by number of digits.

HTH,
0
 
PawełI Design & Develop SoftwareCommented:
you could try this

     static void Main(string[] args)
        {
            Random rnd = new Random();
            var buffer = new byte[(sizeof(Int64))];
            Console.WriteLine(Encoding.Default.GetString(buffer));
            rnd.NextBytes(buffer);
            var num = Math.Abs(BitConverter.ToInt64(buffer, 0));
            Console.WriteLine(num);
         
            Console.WriteLine((num % Math.Pow(10, 16)).ToString("000000000000000"));
        }

i'm really not sure which one is going to have better performance, maybe try both methods and capture some metrics
0
 
sarabandeCommented:
how can I fix the result to 16 digits always?

the Code i posted should guarantee 16 digits because the first of first seven digits is between 1 and 9 :

Int64 i64 = rnd.Next(1000000, 9999999); // this makes the number to have 7 digits

Open in new window


Sara
0
 
JimiJ13I T ConsultantAuthor Commented:
@sarabande

Great! That gives me an idea to modify your solution to get what I want:

Random rnd = new Random();
            Int64 i64 = rnd.Next(10000000, 99999999);
            i64 = (i64 * 100000000) + rnd.Next(0, 999999999);
            this.NewNum.Text = Math.Abs(i64).ToString();

Thanks.
0
 
sarabandeCommented:
but very unique  almost certainly  unique, much more unique then any of the solutions provided
a GUID is a 128 bit number in the range of 0 to 2^128 what is about 3.4 x 10^38. that means the number has at least 37 decimal digits in the range from 0 to 9 each. if you reduce this to 16 digits you will use only the 10^21-th part of this pool what is still a huge number of more than 10 thousand trillion numbers, but any considerations about the uniqueness of the original guid number are out of question.

so if you don't make a methodical mistake, you could be sure that the uniqueness of your random 16-digits key "almost certainly" is guaranteed regardless of the method you were using. you will have to wait for some billion of years to get this to be falsified.

fyi: if you don't 'seed' the random object or 'seed' it with some random seed (say the seconds since 1/1/1970 divided by milliseconds since login), your numbers will always change with the time. if you take a fixed seed, the random series is always the same.

Sara
1
 
JimiJ13I T ConsultantAuthor Commented:
Great solution and invaluable suggestions.
0
 
sarabandeCommented:
the code i posted should guarantee 16 digits
note, if you finally need a string you also could pad numbers with less than 16 digits with leading zeros.

this method actually would use the full range from 0000000000000000 to 9999999999999999 while the other method starts from 1000000000000000.

Sara
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Get expert help—faster!

Need expert help—fast? Use the Help Bell for personalized assistance getting answers to your important questions.

  • 6
  • 4
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now