关于位运算符的运用和理解

      最近看代码发现平时对于位运算符的运用和理解不是特别的清晰,以前在学校里面也学习过这些运算符的用法和介绍,但发现一直都只是比较肤浅的认识他们,对于他们的一些具体的运用不是特别的了解,正好最近需要处理这样的一段代码,从中也深入的学习到了这些运算符的具体用法。所以记录下来方便自己记忆。

      首先,我们来了解一下这两种运算符的一些基本的定义和用法(这里我们不考虑负数)。

      在c++中,移位运算符有双目移位运算符:<<(左移)和>>(右移)。

  1. "<<"左移: 右边空出的位上补0,左边的位将从字头挤掉,其值相当于乘2。
  2. ">>" 右移: 右边的位被挤掉。对于左边移出的空位,如果是正数则空位补0,相当于除2,若为负数,可能补0或补1,这取决于所用的计算机系统。

      按位运算符:&(按位与),|(按位或)和位异或(^)

  1. 按位与-- &
  2. 按位或-- | 
  3. 位异或-- ^

  现在,我们开始通过一个编程的小例子来理解一种比较简单的用法,从中来掌握他们。

  主函数(main):

int _tmain(int argc, _TCHAR* argv[])
{
    CYiWei *pYiwei = new CYiWei();

    int nContextID = 0;
    nContextID = pYiwei->Input();

    pYiwei->OutPut(nContextID);

    system("pause");
    return 0;
}

  CYiWei类:

class CYiWei
{
public:
    CYiWei(void);

    int Input();
    void OutPut(int nContextID);
public:
    ~CYiWei(void);

    enum{
        // int型变量占0-31bit的位置,现在拆分这些bit存取不同的数字
        // 2bit
        nKeyFirst2Bit = 0,
        nKeyFirst2Mask = 0x3 << nKeyFirst2Bit,
        // 4bit
        nKeySecond4Bit = 2,
        nKeySecond4Mask = 0xF << nKeySecond4Bit,
        // 8bit
        nKeyThree8Bit = 6,
        nKeyThree8Mask = 0xFF << nKeyThree8Bit,
        // 16bit
        nKeyFour16Bit = 14,
        nKeyFour16Mask = 0xFFFF << nKeyFour16Bit,
    };

};
#include "StdAfx.h"
#include "YiWei.h"

CYiWei::CYiWei(void)
{
}

CYiWei::~CYiWei(void)
{
}

int CYiWei::Input()
{
    int nContextID = 0;

    nContextID = (1 << nKeyFirst2Bit) | (2 << nKeySecond4Bit) | (3 << nKeyThree8Bit) | (4 << nKeyFour16Bit);

    return nContextID;
}
void CYiWei::OutPut(int nContextID)
{
    int nFirst = (nContextID & nKeyFirst2Mask) >> nKeyFirst2Bit;
    printf("The First 2bit saved data is [%d]\n", nFirst);
    int nSecond = (nContextID & nKeySecond4Mask) >> nKeySecond4Bit;
    printf("The Second 4bit saved data is [%d]\n", nSecond);
    int nThree = (nContextID & nKeyThree8Mask) >> nKeyThree8Bit;
    printf("The Third 8bit saved data is [%d]\n", nThree);
    int nFour = (nContextID & nKeyFour16Mask) >> nKeyFour16Bit;
    printf("The Forth 16bit saved data is [%d]\n", nFour);
}
原文地址:https://www.cnblogs.com/dhls231/p/5633265.html