问题1:不申请变量,实现两个数据的交换。
算法分析:对于这个题目,相信许多人都接触过,如果使用异或操作的话,只要抓住一点:一个数a与另外一个数b异或两次之后,最终的值结果仍然是a。
测试程序&&测试结果:
- ^_^[sunny@sunny-laptop ~/DS/bit_switch]7$ cat first.c
- #include <stdio.h>
-
- int main()
- {
- int a = 12, b = 281;
-
- printf("a=%d,b=%d\n", a, b);
- a = a^b;
- b = a^b;
- a = a^b;
- printf("a=%d,b=%d\n", a, b);
- return 0;
- }
- ^_^[sunny@sunny-laptop ~/DS/bit_switch]8$ ./a.out
- a=12,b=281
- a=281,b=12
- ^_^[sunny@sunny-laptop ~/DS/bit_switch]9$
- ^_^[sunny@sunny-laptop ~/DS/bit_switch]7$ cat first.c
问题2:统计一个整型数据相应二进制的为1的数据位数。
算法分析:一个整型数据是4个字节,16位。从第0位到第15位开始,依次与1想与,如果结果是1,说明这一位是1,将计数器加1。
测试程序&&测试结果:
- ^_^[sunny@sunny-laptop ~/DS/bit_switch]85$ cat second.c
- #include <stdio.h>
-
- int main()
- {
- int a = 67, i, count = 0;
-
- for(i = 0; i < 16; i++) {
- if(a&1 == 1) {
- count++;
- }
- a = a>>1;
- }
- printf("count=%d\n", count);
- return 0;
- }
- ^_^[sunny@sunny-laptop ~/DS/bit_switch]86$ ./a.out
- count=3
- ^_^[sunny@sunny-laptop ~/DS/bit_switch]85$ cat second.c
问题3:将一个十进制的数据转换成二进制数据。
算法分析:
一个
十进制的数据在计算机内就是以二进制的形式存放的,所以没有必要将数据经过一些复杂算法进行转换,只需要将二进制形式存放的数据显示出来就行了。比如要输出x第8位上的对应的二进制数时,将1左移7位,然后让1与x相与,将与的结果再右移7位,强制转换成unsigned类型,加'0'之后,使用putchar()进行输出。
测试程序&&测试结果:
- ^_^[sunny@sunny-laptop ~/DS/bit_switch]21$ cat third.c
- #include <stdio.h>
-
- int main()
- {
- int a = 78, i, count = 0;
-
- for(i = 31; i >=0; i--) {
- putchar('0'+(unsigned)((a&(1<<i))>>i));
- }
- printf("\n");
- return 0;
- }
- ^_^[sunny@sunny-laptop ~/DS/bit_switch]22$ ./a.out
- 00000000000000000000000001001110
- ^_^[sunny@sunny-laptop ~/DS/bit_switch]23$
- ^_^[sunny@sunny-laptop ~/DS/bit_switch]21$ cat third.c
小结:对于c语言位操作的程序设计,这篇博文有关c语言的位操作讲解是比较好的:
相关热门文章
给主人留下些什么吧!~~
评论热议