位操作类
由于在项目中经常用到数据的位操作,因此封装了一个简单的位操作类。如下:
头文件:
#if !defined(AFX_BIT_H__055C5036_21AE_4225_8CC4_921B0C7233C7__INCLUDED_)#define AFX_BIT_H__055C5036_21AE_4225_8CC4_921B0C7233C7__INCLUDED_#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000#pragma pack(push)#pragma pack(1)union u_bit{BYTE Data;struct{BYTE Bit0:1;BYTE Bit1:1;BYTE Bit2:1;BYTE Bit3:1;BYTE Bit4:1;BYTE Bit5:1;BYTE Bit6:1;BYTE Bit7:1;}Bit;};#pragma pack(pop)class CBit{public:CBit();~CBit();// bit置位int SetBit(BYTE bSite);// bit置0int RelBit(BYTE bSite);// 取反int NegBit(BYTE bSite);// 设置数据int SetData(BYTE bData);// 获取数据 BYTE GetData(); u_bit GetUnData(); // 获取bit的值 BYTE GetBit(BYTE bSite); protected:u_bit m_Data;};#endif // !defined(AFX_BIT_H__055C5036_21AE_4225_8CC4_921B0C7233C7__INCLUDED_)
该类私有变量为1字节的联合体数据,可以对数据进行置位, 置0, 数据取反,赋值等操作。
cpp文件
#include "StdAfx.h"#include "Bit.h"CBit::CBit(){m_Data.Data = 0;}CBit::~CBit(){}// bit置位int CBit::SetBit(BYTE bSite){if (bSite > 7){return FALSE;}m_Data.Data |= (1<<bSite);return TRUE;}// bit置0int CBit::RelBit(BYTE bSite){if (bSite > 7){return FALSE;}m_Data.Data &= ((1<<bSite) ^ 0xff);return TRUE;}// 去反int CBit::NegBit(BYTE bSite){if (bSite > 7){return FALSE;}if (GetBit(bSite)){RelBit(bSite);}else{SetBit(bSite);}return TRUE;}// 设置数据int CBit::SetData(BYTE bData){m_Data.Data = bData;return TRUE;}// 获取数据BYTE CBit::GetData(){return m_Data.Data;}u_bit CBit::GetUnData(){return m_Data;}// 获取bit的值BYTE CBit::GetBit(BYTE bSite){if (bSite > 7){return FALSE;}return ((m_Data.Data >> bSite) & 0x1);}