#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;
}
|