与或位运算扩充运算的运用

27 篇文章 0 订阅

与或运算的运行效率是很高的,在程序设计中,经常有一些逻辑判断多重的判断,可能运算效率是很低的,如果数量是有限的32个以内,那么用与或来判断是很快的,如
例1:

if(str == "red" || str == "blue" || str = "white")
{

}

例2:

string[] abc = {"red,str,white ......."};
str = blue;
如果要判断str是否在abc里就要用循环来做.
for(i=0;i<abc.length;i++)
{
	if(str == abc)
	{
		print ("find");
	}
}

如果改成与或来运算,
那么只有abc = 1<<0 | 1 << 1 | 1<< 2;
if(str & int != 0) 就可以知道是否存在于数组中. 节省CPU Cost.

下面是个简单的例子:

using UnityEngine;
using System.Collections;

public class CAndOr : MonoBehaviour {

    int a, b, c, d, e, f;

    int aa,bb,cc,dd,ee,ff;
	void Start () {
        a = 1 << 0;
        b = 1 << 1;
        c = 1 << 2;
        d = 1 << 3;
        e = 1 << 4;
        f = 1 << 5;

        aa = a | b | c | d | e | f;
        bb = b | c | d | e | f;
        cc = c | d | e | f;
        dd = d | e | f;
        ee = e | f;
        ff = f; 
	}
	
    void OnGUI()
    {
        string txt0 = string.Format("a:{0},     b:{1},     c:{2},     d:{3},     e:{4},     f:{5}", a, b, c, d, e, f);
        GUI.Label(new Rect(10, 10, 500, 50), txt0);
        string txt1 = string.Format("aa:{0},     bb:{1},     cc:{2},     dd:{3},     ee:{4},     ff:{5}", aa, bb, cc, dd, ee, ff);
        GUI.Label(new Rect(10, 25, 500, 50), txt1);

        string txt2 = string.Format("aa & a :{0} , aa & b :{1} , aa & c :{2} , aa & d :{3} , aa & e :{4} , aa & f :{5}", aa & a, aa & b, aa & c, aa & d, aa & e, aa & f);
        GUI.Label(new Rect(10, 50, 500, 50), txt2);

        string txt3 = string.Format("bb & a :{0} , bb & b :{1} , bb & c :{2} , bb & d :{3} , bb & e :{4} , bb & f :{5}", bb & a, bb & b, bb & c, bb & d, bb & e, bb & f);
        GUI.Label(new Rect(10, 100, 500, 50), txt3);

        string txt4 = string.Format("cc & a :{0} , cc & b :{1} , cc & c :{2} , cc & d :{3} , cc & e :{4} , cc & f :{5}", cc & a, cc & b, cc & c, cc & d, cc & e, cc & f);
        GUI.Label(new Rect(10, 150, 500, 50), txt4);

        string txt5 = string.Format("dd & a :{0} , dd & b :{1} , dd & c :{2} , dd & d :{3} , dd & e :{4} , dd & f :{5}", dd & a, dd & b, dd & c, dd & d, dd & e, dd & f);
        GUI.Label(new Rect(10, 200, 500, 50), txt5);

        string txt6 = string.Format("ee & a :{0} , ee & b :{1} , ee & c :{2} , ee & d :{3} , ee & e :{4} , ee & f :{5}", ee & a, ee & b, ee & c, ee & d, ee & e, ee & f);
        GUI.Label(new Rect(10, 250, 500, 50), txt6);

        string txt7 = string.Format("ff & a :{0} , ff & b :{1} , ff & c :{2} , ff & d :{3} , ff & e :{4} , ff & f :{5}", ff & a, ff & b, ff & c, ff & d, ff & e, ff & f);
        GUI.Label(new Rect(10, 300, 500, 50), txt7);

        GUI.Label(new Rect(10, 400, 500, 50), (ff & f).ToString());
    }
}

结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值