Chinaunix首页 | 论坛 | 博客
  • 博客访问: 203799
  • 博文数量: 63
  • 博客积分: 2764
  • 博客等级: 少校
  • 技术积分: 620
  • 用 户 组: 普通用户
  • 注册时间: 2009-12-28 21:11
文章分类

全部博文(63)

文章存档

2011年(35)

2010年(28)

我的朋友

分类: C/C++

2010-06-30 17:35:34

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


#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 表示法

阅读(875) | 评论(0) | 转发(0) |
0

上一篇:vi cheat sheet

下一篇:ini文件转换成xml文件

给主人留下些什么吧!~~