文章详情

  • 游戏榜单
  • 软件榜单
关闭导航
热搜榜
热门下载
热门标签
php爱好者> php文档>位操作练习

位操作练习

时间:2010-06-30  来源:lovecreat

今天作的练习题目:都实现了


#include <stdio.h>
//统计一个无符号数二进制表示中1的个数。

int countbit(unsigned int x)
{
        int n=0;
        while ((x = x&(x-1)))
                n++;
        return n+1;
}
//位操作实现无符号整数乘法

unsigned int multiply(unsigned int x, unsigned int y)
{
        int i = 0;
        int s = 0;
        for(i = 0; i < 32; i++)
        {
                if(y>>i & 0x1) {
                        s = s + (x << i);
                }
        }
        return s;
}

//32位无符号整数循环右移

unsigned int rotate_right(unsigned int x, int n)
{
        unsigned int i=0,y=x;
        for(i = 0; i< n; i++)
        {
                if(y&0x1)
                        y=y>>1|0x80000000;
                else
                y=y>>1;
        }
        return y;
}
//不用%x打印无符号整数的16进制数

void ro(unsigned int x)
{
        int i,y;
        for(i = 28; i >= 0; i=i-4)
        {
                y=(x&0xf<<i)>>i;
// printf("y=%x,x=%x, i=%d\n",y,x,i);

                if( y > 9 )
                        printf("%c",y-10+'a');
                else
                        if( y != 0)
                        printf("%c",y+'0');

        }

}
int main(void)
{
        int i=0xffffffff;
        int s=countbit(i);

        unsigned int x=12,y=4,n;
        n = multiply(x,y);
        printf("s=%d\n",s);
        printf("n=%d\n",n);
        printf("%x\n",(i<<2)>>2);
        printf("0xdeadbeef, after:%x \n",rotate_right(0xdeadbeef,8));
        printf("0xf100000f, after:%x \n",rotate_right(0xf100000f,8));

        ro(123);
        printf("\n");
        ro(43981);
        printf("\n");
        return 0;
}


sign and magnitude 表示法
1's complement 表示法
2's complement 表示法

相关阅读 更多 +
排行榜 更多 +
辰域智控app

辰域智控app

系统工具 下载
网医联盟app

网医联盟app

运动健身 下载
汇丰汇选App

汇丰汇选App

金融理财 下载