MiLady
MiLady

Reputation: 45

C# Join 2 Numbers (INT) into 1 longer INT

It might be quite funny but I really didn't know how to search to find the answer for this one.

I always use something like this when I want to join strings "string = "something" + "somethingelse" "

but how to do it with INT? :)

Random r = new Random();
int lvfirst = r.Next(485924948);
int lvsecond = r.Next(39);
int lvdone = lvfirst + lvsecond;
Globals.GlobalInt = lvdone;

I tried doing one long int but it doesn't seem to work it says something about Long so if you can help me how to join this 2 random numbers into 1? I need 1 random number max "48592494839"

Thanks a lot!

Upvotes: 0

Views: 1857

Answers (4)

AK_
AK_

Reputation: 8099

Ignoring the random thing... this is the way to concat to numbers...

int a = 124;
int b = 101040507;

int digits = 32;
mask = 0x80000000;
while(a & mask == 0)
{
    digits--;
    mask= mask >> 1;
}


long result = b;
result = result << digits;
result = result | b;

Upvotes: -1

Jon
Jon

Reputation: 437584

There are two problems with this code:

  1. "Sticking together" two outputs of Next will not give you a random value in the target range. Math does not work with strings.
  2. Instead of returning a result it stores it in a global variable.

If you want a value in the range you specify, use

var result = (long) (r.NextDouble() * 48592494839);

This will still not work for any target range, but it will comfortably meet your specific requirements.

Upvotes: 2

matthewr
matthewr

Reputation: 4739

You could do something like this:

Random r = new Random();
int lvfirst = r.Next(485924948);
int lvsecond = r.Next(39);
long lvdone = Int64.Parse(lvfirst.ToString() + lvsecond.ToString());
Globals.GlobalInt = lvdone;

Basically we are converting all of the ints to a string which will append the second number to the end of the first number, then we convert it back to an int.

Hope this Helps!

Upvotes: 0

Julien Ch.
Julien Ch.

Reputation: 1261

Do you want to add or concatenate your ints ?

If you want to concatenate, you can try:

long lvdone = long.Parse(lvfirst.toString() + lvsecond);

If you want to add them and avoid overflows:

long lvdone = ((long) lvfist) + lvsecond

If you number must be arbitrarily long, try using Decimal instead of long

Upvotes: 0

Related Questions