c# - Using an overflow for modulus with a signed integer -
i'm implementing bunch of different kinds of pseudo random number generators play around with. noticed linear congruential generators can have periods size of int, , thought use overflow instead of modulus , see if it's faster.
the snag overflows overflow sign bit, , need them positive values.
edit: cloudy on couple concepts, i'm cleaning question makes more sense. boils down me trying lop off sign bit of integer. i've found xoring number int.minvalue trick. when has overflowed, if hasn't opposite. i'd avoid if statement though.
if show me nifty trick snag first 31 bits , stuff them integer, delightful. or way set sign bit 0 better?
if want overflow start @ zero, should mask off sign bit.
unchecked { int x = int.maxvalue + 5; int y = x & 0x7fffffff; } console.writeline(y);
this outputs number 4.
i don't think absolute value of overflowed value give want (you go maxint, , descend down, plus, you'll have specially handle int.maxvalue + 1 because equals int.minvalue, math.abs() throw exception on).
unchecked { int x = int.maxvalue + 5; int y = math.abs(x); } console.writeline(y);
this outputs number 2147483644.
Comments
Post a Comment