Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1879322
  • 博文数量: 217
  • 博客积分: 4362
  • 博客等级: 上校
  • 技术积分: 4180
  • 用 户 组: 普通用户
  • 注册时间: 2009-09-20 09:31
文章分类

全部博文(217)

文章存档

2017年(1)

2015年(2)

2014年(2)

2013年(6)

2012年(42)

2011年(119)

2010年(28)

2009年(17)

分类: C/C++

2011-08-28 09:19:17

问题1:不申请变量,实现两个数据的交换。
算法分析:对于这个题目,相信许多人都接触过,如果使用异或操作的话,只要抓住一点:一个数a与另外一个数b异或两次之后,最终的值结果仍然是a。
测试程序&&测试结果:
  1. ^_^[sunny@sunny-laptop ~/DS/bit_switch]7$ cat first.c
  2. #include <stdio.h>

  3. int main()
  4. {
  5.     int a = 12, b = 281;

  6.     printf("a=%d,b=%d\n", a, b);
  7.     a = a^b;
  8.     b = a^b;
  9.     a = a^b;
  10.     printf("a=%d,b=%d\n", a, b);
  11.     return 0;
  12. }
  13. ^_^[sunny@sunny-laptop ~/DS/bit_switch]8$ ./a.out
  14. a=12,b=281
  15. a=281,b=12
  16. ^_^[sunny@sunny-laptop ~/DS/bit_switch]9$
问题2:统计一个整型数据相应二进制的为1的数据位数。
算法分析:一个整型数据是4个字节,16位。从第0位到第15位开始,依次与1想与,如果结果是1,说明这一位是1,将计数器加1。
测试程序&&测试结果:
  1. ^_^[sunny@sunny-laptop ~/DS/bit_switch]85$ cat second.c
  2. #include <stdio.h>

  3. int main()
  4. {
  5.     int a = 67, i, count = 0;

  6.     for(i = 0; i < 16; i++) {
  7.         if(a&1 == 1) {
  8.             count++;
  9.         }
  10.         a = a>>1;
  11.     }
  12.     printf("count=%d\n", count);
  13.     return 0;
  14. }
  15. ^_^[sunny@sunny-laptop ~/DS/bit_switch]86$ ./a.out
  16. count=3
问题3:将一个十进制的数据转换成二进制数据。
算法分析:一个十进制的数据在计算机内就是以二进制的形式存放的,所以没有必要将数据经过一些复杂算法进行转换,只需要将二进制形式存放的数据显示出来就行了。比如要输出x第8位上的对应的二进制数时,将1左移7位,然后让1与x相与,将与的结果再右移7位,强制转换成unsigned类型,加'0'之后,使用putchar()进行输出。
测试程序&&测试结果:
  1. ^_^[sunny@sunny-laptop ~/DS/bit_switch]21$ cat third.c
  2. #include <stdio.h>

  3. int main()
  4. {
  5.     int a = 78, i, count = 0;

  6.     for(i = 31; i >=0; i--) {
  7.         putchar('0'+(unsigned)((a&(1<<i))>>i));
  8.     }
  9.     printf("\n");
  10.     return 0;
  11. }
  12. ^_^[sunny@sunny-laptop ~/DS/bit_switch]22$ ./a.out
  13. 00000000000000000000000001001110
  14. ^_^[sunny@sunny-laptop ~/DS/bit_switch]23$

小结:对于c语言位操作的程序设计,这篇博文有关c语言的位操作讲解是比较好的:




阅读(1530) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~