5

位运算符的应用

 3 years ago
source link: https://gameinstitute.qq.com/community/detail/133473
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

运算符的基本概念和应用

位运算符的定义以及基本的使用可以参考:https://blog.csdn.net/Marccco/article/details/88709481

这边我坐下简要的总结:位运算符有&、|、^、!、~、>>、<<、>>>。

& 与运算符

1. 运算规则:0&0=0;   0&1=0;    1&0=0;     1&1=1;

2. 应用:

① 清零;
② 取一个数中指定位。

| 或运算符

1. 运算规则:0|0=0;   0|1=1;   1|0=1;    1|1=1;

2. 应用:

常用来对一个数据的某些位置1。

^ 异或运算符

1. 运算规则:0^0=0;   0^1=1;   1^0=1;   1^1=0;

2. 应用:
① 使特定位翻转 找一个数,对应X要翻转的各位,该数的对应位为1,其余位为零,此数与X对应位异或即可;
② 与0相异或,保留原值 ,X ^ 0000 0000 = 1010 1110。

~ 取反运算符

1. 运算规则:~1=0;   ~0=1;

2. 应用:

使一个数的最低位为零,可以表示为:a&~1。

<< 左移运算符

运算规则:将一个运算对象的各二进制位全部左移若干位(左边的二进制位丢弃,右边补0),操作数每右移一位,相当于该数乘以2。例如: 二进制的 11111100左移移两位等于二进制的11110000。

>> 右移运算符

运算规则:将一个数的各二进制位全部右移若干位,正数左补0,负数左补1,右边丢弃,操作数每右移一位,相当于该数除以2。例如:二进制的11110010右移两位等于即二进制的 11111100。

>>> 无符号右移运算符

运算规则:右移后左边空出的位用零来填充。移出右边的位被丢弃。例如:二进制的11111111 11111111 11111111 11110010向右移两位后等于二进制的00111111 11111111 11111111 11111100。

案例

/// <summary>

/// 相机约束条件(设置冻结角度/位置)

/// </summary>

[Flags]

public enum CameraConstraints

{

   None = 1,

   FreezePositionX = 2,

   FreezePositionY = 4,

   FreezePositionZ = 8,

   FreezePosition = 16,

   FreezeRotationX = 32,

   FreezeRotationY = 64,

   FreezeRotationZ = 128,

   FreezeRotation = 256,

   FreezeAll = 512

}

int constraints = 0;

float px, py, pz = 0;

Vector3 resultLocalPos = Vector3.zero;

Vector3 resultLocalEulerAngle = Vector3.zero;

public int GetConstraints()

{

   return constraints;

}

public void SetConstraints(int constraints)

{

   this.constraints = constraints;

}

private Vector3 GetFreezePosition() {

   // 获取设备底层的位置信息

   var targetPos = hostSettings.GetPosition(objectName, channel);

   px = targetPos.x;

   py = targetPos.y;

   pz = targetPos.z;

   if ((constraints & (int)CameraConstraints.FreezePositionX) == (int)CameraConstraints.FreezePositionX)

   {

        px = 0;

    }

   if ((constraints & (int)CameraConstraints.FreezePositionY) == (int)CameraConstraints.FreezePositionY)

   {

       py = 0;

    }

   if ((constraints & (int)CameraConstraints.FreezePositionZ) == (int)CameraConstraints.FreezePositionZ)

   {

       pz = 0;

    }

   resultLocalPos.x = px;

   resultLocalPos.y = py;

   resultLocalPos.z = pz;

   return resultLocalPos;

}

外部调用SetConstraints接口设置,比如:(int)(CameraConstraints.FreezePositionX|CameraConstraints.FreezePositionY)。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK