views:

286

answers:

3

I have a 128-bit number stored as 2 64-bit numbers ("Hi" and "Lo"). I need only to divide it by a 32-bit number. How could I do it, using the native 64-bit operations from CPU?

(Please, note that I DO NOT need an arbitrary precision library. Just need to know how to make this simple division using native operations. Thank you).

A: 
64t hi, lo;
32t div;

64t rhi = hi/div;
64t rlo = hi % div + lo/div;

Right?

(A+B)/C = A/C + B/C. Then take the remainder bits from the high order division and add it on to the low order bits.

Dave
Shouldn't that be rlo = (hi%div * 2^64 + lo)/div ?
jon hanson
This is what I thought at first, but with "hi = 0x1" and "lo = 0xFFFFFFFFFFFFFFFF" this solutions causes an overflow :( (1 + 0xFFFFFFFFFFFFFFFF)
rookie
Damn! Where the hell did I put that Knuth's copy?
rookie
@rookie: you're not dividing though.
jon hanson
well. Good try, but you do not get the low order bits doing a modulus. I thought of something like (hi%div) * (2**64/div) + (lo/div) but it doesn't work either because 2**64 is overflowing 64 bits. (hi%div) * 2 * (2**63/div) + (lo/div) is better but loose some bits...
kriss
ah, either way this answer is wrong...
jon hanson
A: 

Some c code here.

jon hanson
+1  A: 

If you are storing the value (128-bits) using the largest possible native representation your architecture can handle (64-bits) you will have problems handling the intermediate results of the division (as you already found :) ).

But you always can use a SMALLER representation. What about FOUR numbers of 32-bits? This way you could use the native 64-bits operations without overflow problems.

A simple implementation (in Delphi) can be found here.

F.D.Castel
Perfect. Thanks!
rookie