关闭

软件乘法

396人阅读 评论(0) 收藏 举报
分类:
#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;
}
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:7269次
    • 积分:159
    • 等级:
    • 排名:千里之外
    • 原创:7篇
    • 转载:0篇
    • 译文:0篇
    • 评论:4条
    文章分类
    最新评论