Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
Solved

# Generate Int64 random numbers

Posted on 2016-08-10
Medium Priority
186 Views
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
Question by:JimiJ13
[X]
###### Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

• Help others & share knowledge
• Earn cash & points
• 6
• 4
• 3
• +1

LVL 10

Assisted Solution

Paweł earned 500 total points
ID: 41750178
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

LVL 35

Accepted Solution

sarabande earned 1000 total points
ID: 41750241
or

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

Sara
0

LVL 64

Expert Comment

ID: 41750300
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

Author Comment

ID: 41751400
@Paweł & @sarabande

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

Thanks.
0

Author Comment

ID: 41751403
@Fernando Soto

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

Thanks.
0

LVL 64

Assisted Solution

Fernando Soto earned 500 total points
ID: 41751454
Hi JimiJ13;

``````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));
``````
0

LVL 10

Expert Comment

ID: 41751487
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

Author Comment

ID: 41751493
@Fernando Soto

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

Thanks.
0

Author Comment

ID: 41751529
@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

LVL 10

Expert Comment

ID: 41751564
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

LVL 35

Expert Comment

ID: 41751570
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
``````

Sara
0

Author Comment

ID: 41751608
@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

LVL 35

Expert Comment

ID: 41751610
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

Author Closing Comment

ID: 41751612
Great solution and invaluable suggestions.
0

LVL 35

Expert Comment

ID: 41751620
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

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction Although it is an old technology, serial ports are still being used by many hardware manufacturers. If you develop applications in C#, Microsoft .NET framework has SerialPort class to communicate with the serial ports.  I needed to…
This article describes a simple method to resize a control at runtime.  It includes ready-to-use source code and a complete sample demonstration application.  We'll also talk about C# Extension Methods. Introduction In one of my applications…
In this video you will find out how to export Office 365 mailboxes using the built in eDiscovery tool. Bear in mind that although this method might be useful in some cases, using PST files as Office 365 backup is troublesome in a long run (more on t…