Subtracting unsigned 64bit numbers

BlitzMax Forums/BlitzMax Programming/Subtracting unsigned 64bit numbers

ImaginaryHuman(Posted 2006) [#1]
I have code working that adds two unsigned 64-bit numbers together, by splitting them into two separate 32-bit numbers (stored in two Longs each), adding those split parts, adding any overflow from the lower part to the upper part, and then combinging them (or).

I am trying to do the same thing with subtracting the two numbers but it's proving a bit difficult.

Both numbers are 64-bit unsigned and must remain so. One number is subtracted from the other, and then there are actions to take based on the result. If the result would be <0, 2^64 should be added to the value to `wrap it`, or in another case, if the number is <0 it becomes zero (easy enough). I achieve this I don't want a whole bunch of If statements, it should be done using shifts, and's, or's, etc.

I just cant quite figure out the combination to split the data up, do the subtraction and preserve the sign, then combine it all back together properly. The end result has to be written out to memory.

So I just thought I'd throw it out there, maybe someone can suggest a technique? I also have to do the same thing to accomodate 63-bit numbers.

Thanks


FlameDuck(Posted 2006) [#2]
Is there any particular reason you can't just subtract them from each other using the minus operator?


Yan(Posted 2006) [#3]
b = 100
c = 5

Print b - c 
Print b + (~c + 1)



ImaginaryHuman(Posted 2006) [#4]
What does ~ do?

The reason you can't subtract them is because if the number being subtracted is bigger than the number being subtracted from, it would make a negative number, the data would suddenly be stored with the 64th bit set and in the format for negative numbers. This would corrupt the data. I can't have it changing the 64th bit. I need to subtract two UNSIGNED 64-bit numbers, which use ALL 64 bits, not 63.

ie I have a number stored, let's say it could be 2^64-1 ... technically if that number is stored in a Long, it will not read as the unsigned value 2^64-1, it will read as minus something because the uppermost bit is set. That messes up the math.

I have numbers ranging from 0 to 2^64-1, unsigned. They are stored in 64 bits of data. They happen to be read in from memory into a Long. Obviously interpreting the Long with regular math will read it wrong. I need to treat the whole thing as an unsigned value, subtract it from another similar number, take some steps based on whether the number is <0, and then write out the unsigned result - which could be 2^64-1, using a Long.

So how do I do that?


Stuart Morgan(Posted 2006) [#5]
What does ~ do?

Bitwise exclusive or


ImaginaryHuman(Posted 2006) [#6]
I'll give it a try.