Chinaunix首页 | 论坛 | 博客
  • 博客访问: 258760
  • 博文数量: 107
  • 博客积分: 305
  • 博客等级: 二等列兵
  • 技术积分: 417
  • 用 户 组: 普通用户
  • 注册时间: 2008-08-22 09:42
文章分类

全部博文(107)

文章存档

2014年(3)

2013年(41)

2012年(34)

2011年(28)

2008年(1)

分类: C/C++

2013-10-24 13:43:07

         最近一直都没写什么文章,随便写点最近看到的东西。首先要提一点,在SOC系统中,运算速度一般是移位>乘法>除法。
         1.乘法。
          最简单的A*B,用C语言for循环
          for(int i=0;i           这个是最容易想到的,现在用移位来实现,效率要高一点。

          例子1.计算A*17
           法1:A=A<<4+A;//移位一次相当于*2
           法2:模拟二进制乘法手动运算,适合大整数的乘法。
                   以前写汇编的时候就写过,利用内存单元(1个byte)来存储乘法的一个位值。
                    与低位相乘,无非得到原数和0.再做一个大整数的加法,自己判断是否进位了。
                    大家有兴趣自己实现下。
            2.除法
            最简单的除法实现A/B,也是用一个for循环
            for(int i=0;A>0;A-=B) i++;
            移位当然只能实现2的倍数的除法了。
            例子2.计算A/8
            A>>3
            那么计算其它的怎么办呢。本文主要是针对整形除法的,假如做浮点数运算,可以考虑如下,将其分子分母进行一定10的倍数的扩大,结果进行些处理就好了。
            写了个简单的代码,模仿手动做除法的过程。
            struct NUM
          {
        int result; //保存商的每一次减法结果
        int remainder;//最后的余数
          };  
         struct NUM divde(int div_1,int div_2)
      {
       //just do int type divide,for float, you can extend the remain value
      //default div_2 bigger than div_1
       int tmp_1=div_1;//keep the high bit
       int count_1=0;
        int tmp_2=div_2;
       struct NUM num;
         num.result=0x00;


        while((tmp_1=tmp_1<<1)<=tmp_2)
        count_1++;//left aligned


       tmp_1=tmp_1>>1;//recovery
       // printf("%d %d",tmp_1,count_1);
       for(;count_1>=0;count_1--)
       {   
            if(tmp_2>=tmp_1){
            tmp_2=tmp_2-tmp_1;
           tmp_1=tmp_1>>1;//new round
             num.result+=(0x01<           }//if
          else
            {
           tmp_1>>1;
                continue;


            }//else if
        }//for
        num.remainder=tmp_2;
        return num;
          }
            void main()
        {       


       int div_1=0,div_2=0;
        struct NUM num;
        printf("please input two number to divede(result no less than 1)\n");
        scanf("%d %d",&div_1,&div_2);
        if(div_1>div_2)
           {  
              div_1=div_1^div_2;
              div_2=div_1^div_2;
             div_1=div_1^div_2;
            }//simple switch
        num=divde(div_1,div_2);
        printf("\n%d / %d =%d----%d",div_2,div_1,num.result,num.remainder);
          
        }  
        代码直接从编辑器拷贝来的,转贴来就这样了,代码思路大概这样:1.小一点的数先移位对齐大一点的数,记下对齐移位的次数,
        2.然后被除数减去除数,本次的商被记录为num.result+=(0x01<         并且小数右移一位。
        3.余数最后存储在tmp_2做减法的最后结果中。
        注:要做大整数除法其实也是类似的思想,只不过操作的基本元素-位换成了内存单元了。

         今天要说的基本就是这些了,希望对大家有用。。。。




阅读(830) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~