zoukankan      html  css  js  c++  java
  • C语言位运算实现函数体

    /*1、用位操作实现无符号整数的乘法运算,函数原型是unsigned int multiply(unsigned int x, unsigned int y);。例如:(11011)2×(10010)2=((11011)2<<1)+((11011)2<<4)。 (unsigned int 占用4个字节,共32位)*/ #include unsigned int multiply(unsigned int a,unsigned int b) { int c =0,i = 0; for (;i < 32;i ++ ) { if(b&1) // 判断最低位是否为1 { c = c + (a << i );//移i位相加 b>>=1;//b右移1位 } else { b>>=1; } } return c ; } int main () { unsigned int x,y; printf("Please input x and y value:"); scanf("%u%u",&x,&y); printf("自动实现:%d*%d=%d ",x,y,x*y); printf("函数实现:%d*%d=%d ",x,y, multiply(x,y)); return 0; } /*2、对一个32位无符号整数做循环右移,函数原型是unsigned int rotate_right(unsigned int x, int n); 所谓循环右移就是把低位移出去的部分再补到高位上去,例如rotate_right(0xdeadbeef, 8)的值应该是0xefdeadbe。*/ #include unsigned int rotate_right(unsigned int x, int n); int main() { unsigned int x; int n ; printf("Please input x and n:"); scanf("%u%d",&x,&n); printf("x:%u ",rotate_right(x, n)); return 0; } unsigned int rotate_right(unsigned int x, int n) { for (int i = 0;i < n ;i ++)// 循环n位 { if (x&1)//判断最低位是否时1,如果是1就移到最高位,最高位加1 { x = x >> 1; x = x + 0x80000000;//x+=1<<31; } else { x = x >> 1; } } return x; }
  • 相关阅读:
    Java 重载机制
    网关、DNS、子网掩码、MAC地址、路由器、猫
    前台?后台?前端?后端?
    JSP初学
    PS笔记
    Pandorabox等类OpenWrt的路由器 实现后端设备接入IPV6(中继代理+NAT)
    三星S5_G9008V 解锁联通4G(安卓6.0)
    一个意外的发现
    硬改路由器-MW310R-AR9341篇
    关于使用硬改的路由器的各种经历
  • 原文地址:https://www.cnblogs.com/qingpeng-ios/p/4131989.html
Copyright © 2011-2022 走看看