# Wrapping ulong variables with arithmatic operators

0

I'm somewhat confused regarding the nature of intentionally overflowing structures like ulong in C#.

Essentially I'm working on a grid that I want to be ulong.max X ulong.max squares. If I perform an arithmetic operation on the coordinates I want it to automatically wrap over the other side of the grid. However, it seems if I multiply two ulongs together and it results in an overflow, I end up with zero instead of the "modulus(ulong.max)" of whatever I would have otherwise. Maybe I misunderstand what is supposed to happen when I overflow a 64 bit ulong.

Any help on ways to make a wrapping coordinate system for a grid that allow the numbers to automatically wrap around would be great. Maybe this isn't possible?

I'm feeding in "longs" and converting them to "ulongs" bitwise which ends up with coordinates like:

(-1,0) = (0xFFFFFFFF, 0x00000000)

(-2,0) = (0xFFFFFFFE, 0x00000000)

Anyway, any pointers on ways to make a fully wrapping coordinate grid would be helpful. Maybe my brain simply isn't working today and I'm missing something obvious that's causing it to go haywire at high ulong numbers.

c#
overflow
word-wrap
ulong

0

However, it seems if I multiply two ulongs together and it results in an overflow, I end up with zero instead of the "modulus(ulong.max)" of whatever I would have otherwise.

You wouldn't get the result `modulus(ulong.max)` - you would get the result `modulus(ulong.max + 1)`.

For example:

``````ulong x = 10000000000L;
ulong y = 2000000000L;
Console.WriteLine(x * y); // 1553255926290448384
``````

Basically, wrap-around works exactly as you should expect it to.

I would recommend using `byte` for simpler examples though. For example:

``````byte x = 150;
byte y = 2;
byte z = (byte) (x * y); // 44 (300 % 256)
``````

It's easier to think of 255 + 1 wrapping to 0 than it is to have to think about 18446744073709551615. But fundamentally they will behave the same way (after a cast - otherwise "`byte` arithmetic" is actually performed after promotion to `int` - that doesn't happen with `ulong`, of course.)

User contributions licensed under CC BY-SA 3.0