代码农工~KingXF

愿与大家互帮互助。

软件乘法

#include <stdint.h>
#include <stdbool.h>


uint64_t _soft_umul_bad(uint32_t a, uint32_t b)
{
    uint64_t ret = 0;
    int i, j;

    for (i = 0; i < sizeof(a)*8; i++)
        for (j = 0; j < sizeof(b)*8; j++)
        {
            ret += (uint64_t)((a & (1 << i)) && (b & (1 << j))) << (i + j);
        }
    return ret;
}


uint64_t _soft_umul(uint32_t a, uint32_t b)
{
    uint64_t ret = 0, shift;
    int i;

    shift = b;

    for (i = 0; i < sizeof(b)*8; i++)
    {
        if(a & (1 << i))
        {
            ret += shift;
        }
        shift <<= 1;
    }
    return ret;
}


int64_t _soft_mul(int32_t a, int32_t b)
{
    bool neg_a, neg_b, neg_re;
    int64_t ret;

    neg_a = (a < 0);
    neg_b = (b < 0);
    neg_re = neg_a ^ neg_b;

    a = neg_a ? (-a) : (a);
    b = neg_b ? (-b) : (b);

    ret = (int64_t)_soft_umul((uint32_t)a, (uint32_t)b);
    return neg_re ? (-ret) : (ret);
}




#include <stdio.h>


int main(int argc, char *argv[])
{
    int32_t a, b;
    int64_t re_soft, re;
    if (argc != 0)
    {
        fprintf(stderr, "softmul [num1] [num2]\n");
        return -1;
    }

    sscanf(argv[1], "%d", &a);
    sscanf(argv[2], "%d", &b);

    re = (int64_t)a * b;
    re_soft = _soft_mul(a, b);

    printf("a = %d, b = %d\n", a, b);
    printf("re = %lld, re_soft = %lld\n", re, re_soft);

    return 0;
}
阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u013097499/article/details/46813207
个人分类: 短代码仓库
想对作者说点什么? 我来说一句

汇编长整数乘法

2018年06月17日 5KB 下载

没有更多推荐了,返回首页

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭