java编程中使用二进制进行权限或状态控制

直接看代码以及注释吧。

    @Test
    public void main() {
        // PC WEB端
        int pc = 1 << 0;// ...0001=1

        // Android端
        int android = 1 << 1;// ...0010=2

        // iOS端
        int ios = 1 << 2;// ...0100=4

        // WindowsPhone
        int wp = 1 << 3;// ...1000=8

        //----------------校验开始-----------------
        //表示只适用于PC WEB端
        int pcAndAndroid = pc | android;
        //判断是否有android端
        System.out.println((pcAndAndroid & android) == android);// true
        //判断是否有ios
        System.out.println((pcAndAndroid & ios) == ios);// false
        //去掉android,加入ios,判断是否有ios,   pcAndAndroid & (~android) 去掉android
        System.out.println((((pcAndAndroid & (~android)) | ios) & ios) == ios);// true
        //去掉android,加入ios,判断是否有android,  false
        System.out.println((((pcAndAndroid & (~android)) | ios) & android) == android);// false

        //--------------
        // android/ios/win phone
        int aiw = android | ios | wp;
        //判断是否有android 并且有win phone
        System.out.println((aiw & (android | wp)) == (android | wp));// true
        //判断是否有android 并且有pc
        System.out.println((aiw & (android | pc)) == (android | pc));// false
    }

顺便看看Oracle数据库怎么弄,比较麻烦咯,不建议这么搞,毕竟数据存进去也得计算一次

位与的操作,在应用程序里是经常会用到的, 
Oracle也提供这样的函数 
BITAND(x,y) 
SQL> select bitand(7, 31) from dual; 
BITAND(7,31) 
------------ 
7 
但是Oracle里没有提供bitOr的函数,没关系 
bitand和bitOR是有关系的。 
关系如下 
BITOR(x,y) = (x + y) - BITAND(x, y); 
BITXOR(x,y) = BITOR(x,y) - BITAND(x,y) = (x + y) - BITAND(x, y) * 2; 
SQL> select 7+31-bitand(7, 31) as bitor from dual; 
BITOR 
---------- 
31 
发布了49 篇原创文章 · 获赞 97 · 访问量 34万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章