Force addition between ulong and long variable

Viewed 295

I have the following function:

long Foo (long min, long max)
{
    ulong range = max - min; // guaranteed to fit in ulong
    ulong x = GenerateRandomULongBetween0AndRange(range);
    return x + min; // result is guaranteed to fit in long
}

But the C# compiler says I cannot add ulong and long. x can be greater than long.MaxValue though, and min may be negative. So I can't cast one to the other. How to proceed? :-(

2 Answers

The C# compiler says I cannot add ulong and long.

Correct.

x can be greater than long.MaxValue though, and min may be negative.

Correct.

So I can't cast one to the other.

Incorrect. Cast them. See what happens! You might be pleasantly surprised.

Long/ulong arithmetic is not different; the bit patterns are exactly the same and it compiles down to the same code. It's just the interpretation of the bits that differs.

One word of warning: it is possible to put C# into a mode where it crashes when there is an overflow involving integer arithmetic, and you explicitly do NOT want that to crash here. You can ensure that this does not happen even if someone turns on "checked by default" by using the unchecked feature in either its expression or statement form.

learn casting 
example
ulong min=2;
ulong range = 12 - 2; // guaranteed to fit in ulong
ulong x = (ulong) range;
long we=  (long)x +(long) min;

    long.MinValue = -9223372036854775808
    long.MaxValue =  9223372036854775807
    18446744073709551615 <-- Max ulong
    0                    <-- Minulong

long can be negative and positive both.

    long range = long.MaxValue - 0; // guaranteed to fit in 
    long x = GenerateRandomLongBetween0AndRange(range);
`x= Math.Abs(x ) to get positive values if you are using long` for that.

Even your function is  ok  just change signature here

    long Foo (long min, long max)
    {
        ulong range = max - min; // guaranteed to fit in long
        ulong x = GenerateRandomULongBetween0AndRange(range);
        return (long) x +(long) min; // result is guaranteed to fit in long
    }
Related