【C++】位操作的应用

// test.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <Windows.h>
#include <iostream>
using namespace std;

#define MAX_ACHIEVE_DATA_SIZE 256   					//成就的最大的BYTE数量
char m_achieveFinishState[MAX_ACHIEVE_DATA_SIZE];       //成就的完成状态和领取奖励的状态

void SetAchieveFinished(INT_PTR nAchieveId)
{
	INT_PTR  nBytePos = nAchieveId >> 2;		//第多少个BYTE
	INT_PTR  nBitPos = (nAchieveId &3) << 1;    //一个BYTE里的第几个Bit
	m_achieveFinishState[nBytePos] |= (BYTE)(1 << nBitPos) ;
}
bool IsAchieveFinished(INT_PTR nAchieveId)
{
	INT_PTR  nBytePos = nAchieveId >> 2;		//第多少个BYTE
	INT_PTR  nBitPos = (nAchieveId & 3) << 1 ;  //一个BYTE里的第几个Bit
	if( m_achieveFinishState[nBytePos] & (BYTE)(1 << nBitPos) )
	{
		return true;
	}
	return false;
}
//是否已经领取过成就的奖励了
inline bool IsAchieveGiveAwards(INT_PTR nAchieveId)
{
	INT_PTR  nBytePos = nAchieveId >> 2; //第多少个BYTE
	INT_PTR  nBitPos = ((nAchieveId &3) << 1) +1;  //一个BYTE里的第几个Bit
	if( m_achieveFinishState[nBytePos] & (BYTE)(1 << nBitPos) )
	{
		return true;
	}
	return false;
}
//设置已经领取过成就的奖励了
inline bool SetAchieveGiveAwards(INT_PTR nAchieveId)
{
	INT_PTR  nBytePos = nAchieveId >> 2;			//第多少个BYTE
	INT_PTR  nBitPos = ((nAchieveId &3) <<1) +1;	//一个BYTE里的第几个Bit
	m_achieveFinishState[nBytePos] |=  (BYTE)( 1 << nBitPos );
	return true;
}
int _tmain(int argc, _TCHAR* argv[])
{
	int nAchieveId = 1;
	SetAchieveFinished( nAchieveId);
	SetAchieveGiveAwards(nAchieveId);
	cout<<IsAchieveFinished(nAchieveId)<<endl;
	cout<<IsAchieveGiveAwards(nAchieveId)<<endl;
	nAchieveId = 2;
	cout<<IsAchieveFinished(nAchieveId)<<endl;
	cout<<IsAchieveFinished(nAchieveId)<<endl;
	system("pause");
	return 0;
}


 

Tint32 setb_1(Tint32 a,Tint32 n)
{
	n--;
	if(n<0 || n>=32)
	{
		return 0;
	}
	Tint32 nMask = (Tint32)0x1 << (Tint32)n;
	a |= nMask;
	return a;
}

Tint32 getb(Tint32 a, Tint32 n)
{
	n--;
	if(n<0 || n>=32)
	{
		return false;
	}
	Tint32 nMask = (Tint32)0x1 << (Tint32)n;
	return (a&nMask) == nMask;
}

Tint32 getn_1(Tint32 a)
{
	int count =0;
	while (a)
	{
		count++;
		a=a&(a-1);
	}
	return count;	
}
原文地址:https://www.cnblogs.com/byfei/p/14104263.html