几个位操作的例子

本文介绍了C语言中三个实用的位操作技巧:不使用额外变量交换两个数;统计整数中1的个数;以及将十进制数转换为二进制显示。通过具体的代码示例展示了这些操作的具体实现。
问题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$
问题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
问题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$

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




<script>window._bd_share_config={"common":{"bdsnskey":{},"bdtext":"","bdmini":"2","bdminilist":false,"bdpic":"","bdstyle":"0","bdsize":"16"},"share":{}};with(document)0[(getelementsbytagname('head')[0]||body).appendchild(createelement('script')).src='http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion='+~(-new date()/36e5)];</script>
阅读(799) | 评论(0) | 转发(1) |
给主人留下些什么吧!~~
评论热议
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值