使用移位运算符分割一个大小数

时间:2021-11-29 00:38:03

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

如何用c编写一个程序来使用移位运算符分割一个大的数字?

For example we need to split a large number like 12345678 into two smaller digits 1234 and 5678 using only bit shift operations and not using the normal n=n*10 and n=n%10 technique. How would you do that?

例如,我们需要将一个大的数字(如12345678)分割成两个较小的数字(1234和5678),只使用位移位操作,不使用普通的n=n*10和n=n%10技术。你会怎么做?

2 个解决方案

#1


1  

You can use standard long division algorithm and call it with 12345678 and 10000. If you want to optimize it for dividing by 10000 only, pre-evaluate it for b == 10000 by hand.

您可以使用标准的长除法算法,将它调用为12345678和10000。如果你想对它进行优化,只除以10000,用手工对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);
}

#2


0  

You can convert number to BCD representation and then use shift operations to split them into two variables.

您可以将数字转换为BCD表示形式,然后使用移位操作将它们分割为两个变量。

BCD Conversion using shift operator only.

只使用移位操作符进行BCD转换。

#1


1  

You can use standard long division algorithm and call it with 12345678 and 10000. If you want to optimize it for dividing by 10000 only, pre-evaluate it for b == 10000 by hand.

您可以使用标准的长除法算法,将它调用为12345678和10000。如果你想对它进行优化,只除以10000,用手工对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);
}

#2


0  

You can convert number to BCD representation and then use shift operations to split them into two variables.

您可以将数字转换为BCD表示形式,然后使用移位操作将它们分割为两个变量。

BCD Conversion using shift operator only.

只使用移位操作符进行BCD转换。