且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

【Programming Clip】位运算的应用

更新时间:2022-09-13 22:14:46

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/archive/2012/01/09/2317369.html,如需转载请自行联系原作者