zoukankan      html  css  js  c++  java
  • 【Programming Clip】位运算的应用

    作者:gnuhpc
    出处:http://www.cnblogs.com/gnuhpc/

    1.用途

    利用位运算,完成判断两个数字直接二进制的差异,数值交换,判断是否为2的次方,以及判断机器是SMALL_ENDIAN还是BIG_ENDIAN等。

    2.描述语言

    C++

    3.原理

    这个也没有什么原理,就是位运算,包括位移、与、或、异、取反或等。

    4.代码

    /*
     * =====================================================================================
     *        Version:  1.0
     *        Created:  01/09/2012 02:30:34 PM
     *       Revision:  none
     *       Compiler:  gcc/g++
     *
     *         Author:  gnuhpc (http://www.cnblogs.com/gnuhpc), gnuhpc#gmail.com
     *        Company:  CMBC
     *
     * =====================================================================================
     */
    #include <iostream>
    #include <vector>
    #include <set>
    #include <algorithm>
    #include <fstream>
    #include <cstdlib>
    #include <cctype>
    #include <sstream>
    #include <numeric>
    #include <map>
    
    using namespace std;
    
    int bitDiff(int a,int b)
    {
    	int result=0;
    	for (int i = a^b;i!=0;i>>=1)
    	{
    		result+=i&1;
    	}
    	return result;
    }
    
    void swap(int& a, int& b)
    {
    	if (a!=b)
    	{
    		a=a^b;
    		b=a^b;
    		a=a^b;
    	}
    }
    
    bool judgepower2(int n)
    {
    	return (n&(n-1))==0;
    }
    
    int ByteOrder()
    {
    	//return 0 for BIG_ENDIAN -- the most significant byte in the smallest address
    	//return 1 for SMALL_ENDIAN-- the least significant byte in the smallest address
    	short int word = 0x0001;
    	char *byte = (char*) &word;
    	return (byte[0]?1:0);
    }
    
    int main()
    {
    	int m = 12; //00001100
    	int n = 134;//10000110
    	cout << bitDiff(m,n) <<endl;
    	swap(m,n);
    	cout <<"m=" <<m <<",n=" << n<<endl;
    
    	cout.setf(ios::boolalpha);
    	cout << judgepower2(64) <<endl;
    	cout << judgepower2(6) <<endl;
    
    	cout << ByteOrder() <<endl;
    	return 0;
    }
    

    5.收获

    1)在处理数值需要提高效率时可以从二进制的规律考虑,进行程序优化。

    2)g++下,左移的规则是:向左移动,不管是否为符号位,丢弃最高位,低位补齐。左移一位相当于乘以2,由于int在C中是有符号的,最高位是符号位,0为正,1为负,所以左移可能产生溢出,即超过最大能表示的范围而变为了负值。

    3)g++下,右移的规则是:向右移动,符号位正数补0负数补1(其实就是符号位不变),不存在溢出。

    4)当位移的位数超过该数值类型的最大位数时,编译器会用位移位数去模类型的最大位数,然后按余数进行移位。

    6.代码下载

    http://gnuhpc.googlecode.com/svn/trunk/CPPExClip/bitopeartion.cpp


                   作者:gnuhpc
                   出处:http://www.cnblogs.com/gnuhpc/
                   除非另有声明,本网站采用知识共享“署名 2.5 中国大陆”许可协议授权。


    分享到:

  • 相关阅读:
    linux strace 命令详解
    Redis执行Lua脚本示例
    getconf
    rc.sysinit 解析
    Linux系统启动内幕
    syslinux 和 grub
    isolinux.cfg 文件是干什么的
    C++中构造函数调用构造函数
    static和extern的作用域--题目
    构造函数与析构函数不能被继承
  • 原文地址:https://www.cnblogs.com/gnuhpc/p/2317369.html
Copyright © 2011-2022 走看看