日期:2014-05-16 浏览次数:20735 次
1、统计一个无符号整数的二进制表示中1的个数,函数原型是int countbit(unsigned int x);
#include<stdio.h> int countbit(unsigned int x) { int i = 0; int count = 0; int mask = 0x00000001; for (i = 0; i < 32; i++) { if ( 1 == (x >> i & mask)) count++; } return count; } int main() { printf ("%d\n",countbit (0x23)); }
unsigned int multiply(unsigned int x, unsigned int y);
。例如:(11011)2×(10010)2=((11011)2<<1)+((11011)2<<4)。
#include<stdio.h> unsigned int multiply(unsigned int x, unsigned int y) { int i; int result = 0; int mask = 0x00000001; for (i = 0; i < 32; i++) { if ( 1 == (x >> i & mask)) result = result + (y << i); } return result; } int main() { printf ("%d\n",multiply (9, 2)); }
3、对一个32位无符号整数做循环右移,函数原型是
unsigned int rotate_right(unsigned int x,
int n);
。所谓循环右移就是把低位移出去的部分再补到高位上去,例如rotate_right(0xdeadbeef, 8)
的值应该是0xefdeadbe。
#include<stdio.h> unsigned int rotate_right(unsigned int x, int n) { int i; int mask = 1; for (i = 1; i < n; i++) { mask = ((mask << 1) | 1); } unsigned int y = (x >> n) | ((x & mask) << (32 - n)); return y; } int main() { printf ("%x\n",rotate_right(0xdeadbeef, 8)); return 0; }