#include <stdio.h>
typedef struct {
int flag; // 0:負、1:正
unsigned int upper;
unsigned int lower;
} w_int;
void DivFunc(w_int* pNumA, w_int* pNumB)
{
w_int q, r;
int i;
if (pNumB->upper == 0 && pNumB->lower == 0) return;
q.upper = q.lower = 0;
r.upper = r.lower = 0;
for (i = 63; 0 <= i; i--) {
r.upper <<= 1;
r.upper |= r.lower >> 31;
r.lower <<= 1;
if (32 <= i) {
r.lower |= (pNumA->upper >> (i - 32)) & 1;
} else {
r.lower |= (pNumA->lower >> i) & 1;
}
if (r.upper < pNumB->upper) continue;
if (r.upper == pNumB->upper && r.lower < pNumB->lower) continue;
r.upper -= pNumB->upper;
if (r.lower < pNumB->lower) r.upper--;
r.lower -= pNumB->lower;
if (32 <= i) {
q.upper |= 1 << (i - 32);
} else {
q.lower |= 1 << i;
}
}
q.flag = !(!pNumA->flag ^ !pNumB->flag);
r.flag = 1;
*pNumA = q;
*pNumB = r;
}
int main()
{
w_int n, d;
long long ln, ld, lq, lr;
n.flag = 1;
n.upper = 123;
n.lower = 456;
d.flag = 1;
d.upper = 7;
d.lower = 89;
printf("n=%d %#x %#x\n", n.
flag, n.
upper, n.
lower); printf("d=%d %#x %#x\n", d.
flag, d.
upper, d.
lower);
ln = ((n.flag << 1) - 1) * (((long long)n.upper << 32) + n.lower);
ld = ((d.flag << 1) - 1) * (((long long)d.upper << 32) + d.lower);
lq = ln / ld;
lr = ln % ld;
printf("ln=%#llx ld=%#llx lq=%#llx lr=%#llx\n", ln
, ld
, lq
, lr
);
DivFunc(&n, &d);
printf("n=%d %#x %#x\n", n.
flag, n.
upper, n.
lower); printf("d=%d %#x %#x\n", d.
flag, d.
upper, d.
lower);
return 0;
}
/*
unsigned int n, d, q, r;
int i;
n = 10;
d = 3;
if (d == 0) return 1;
q = 0;
r = 0;
for (i = 31; 0 <= i; i--) {
r <<= 1;
r |= (n >> i) & 1;
if (r >= d) {
r -= d;
q |= 1 << i;
}
}
*/
I2luY2x1ZGUgPHN0ZGlvLm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