C++快速判断二进制某位是1或0

      其实原理很简单,1BYTE = 8bit,bit是二进制,根据8421编码就很容易得出相对应的位,8bit中分为高4位和低4位,这样可以从低位到高位 bit0-bit7 得到表示为:

       0x01 0x02 0x04 0x08 0x10 0x20 0x40 0x80

#include 
using namespace std;

typedef unsigned char UINT8;


// 判断某位是否为1
bool JudgeBitIsOne(UINT8 ucData, UINT8 ucFlag)
{
	if (0x00 == ucData)
		return false;
	else if (ucData == ucFlag)
		return true;
}

int _tmain(int argc, _TCHAR* argv[])
{
	UINT8 ucTemp = 0xF2; // 1111 0010

	// bit0-bit7 0x01 0x02 0x04 0x08 0x10 0x20 0x40 0x80
	cout << JudgeBitIsOne((ucTemp & 0x01), 0x01) << " ";
	cout << JudgeBitIsOne((ucTemp & 0x02), 0x02) << " ";
	cout << JudgeBitIsOne((ucTemp & 0x04), 0x04) << " ";
	cout << JudgeBitIsOne((ucTemp & 0x08), 0x08) << " ";
	cout << JudgeBitIsOne((ucTemp & 0x10), 0x10) << " ";
	cout << JudgeBitIsOne((ucTemp & 0x20), 0x20) << " ";
	cout << JudgeBitIsOne((ucTemp & 0x40), 0x40) << " ";
	cout << JudgeBitIsOne((ucTemp & 0x80), 0x80) << " " << endl;
	return 0;
}
      得到的运算结果为:





你可能感兴趣的:(c++/c)