Divide large decimal using shift operator

How to write a program in c to split a large number using the shift operator?

For example, we need to break a large number, for example 12345678, into two smaller digits 1234 and 5678, using only bit shifting operations and not using the usual n = n * 10 and n = n% 10. How will you do this?

+4
source share
2 answers

You can use the standard long division algorithm and call it 12345678 and 10000. If you want to optimize it to divide only by 10000, first evaluate it manually for b == 10000.

void div(int a, int b) {
    int d, res;
    d = 1;
    res = 0;
    while (b > 0 && b < a) {
        b <<= 1;
        d <<= 1;
    }

    do {
        if (a >= b) {
            a -= b;
            res += d;
        }
        b >>= 1;
        d >>= 1;
    } while (d);

    printf("Result: %d, reminder: %d\n", res, a);
}

int main() {
    div(12345678, 10000);
}
+1
source

All Articles