位运算的几点用处

还在自学Java中,暂不明白位运算有哪些用处,上午上已经工作的朋友请教,了解了几个运用位运算的场景,日后如果有更多例子,再行添加。


1.乘以2,除以2

i<<1和>>1的效率比i*2和i/2更高。

i<<N效率比2^N效率更高。


2. 产生-1 -2 -3...min  -1 -2.......的序列

这是某通信系统中用到的序列

import java.util.concurrent.atomic.AtomicInteger;
public class Bit2{
    public static void main(String[] args){
        int flag = 1; //用于输出数字
        int min = -(1 << 28); //由负数的解码方法可知,加负号相反于取反再加1,此时第29位和29以上都是1,28和28位以下都是0
        int num;
        AtomicInteger ai = new AtomicInteger(min+3); //线程安全的类,可用于自减
        while(flag++ <= 10){
            num = ai.getAndDecrement();
            num = num | min; //由负数的解码方法可知,29和29位以上的1解码后都代表0。此法相当于将29和29位以上都置0,将原数限制在28和28位以下。
            System.out.println(num);
        }
    }
}

------Output------
-268435453
-268435454
-268435455
-268435456
-1
-2
-3
-4
-5

-6

上面程序还有一种逻辑上更易理解的写法:

import java.util.concurrent.atomic.AtomicInteger;
public class Bit2{
    public static void main(String[] args){
        int flag = 1; //用于输出数字
        int max = (1 << 28) -1;  //减1后,28和28位以下都为1
        int num;
        AtomicInteger ai = new AtomicInteger(-4); //线程安全的类,可用于自减
        while(flag++ <= 10){
            num = ai.getAndIncrement();
            num = ~(num & max); //按位与运算将原数字限制在28和28位以下,括号中原值域是0~2^29-1,按位取反后值域为-1~ -(2^29),正好去掉了0
            System.out.println(num);
        }
    }
}



3.权限控制

某群友给的题:

在Linux下的权限,分为读,写,执行,分别对应4,2,1。
那么任意给一个0~7的数字,计算出该数字具有的权限。(位运算)
显示结果:
您的权限为:5
您具有:读 执行 的权限

public class T{
    public static void main(String[] args){
        check(5);
    }

    static void check(int n){
        StringBuilder sb = new StringBuilder();
        if( (n & 4) == 4) sb.append("读 ");
        if( (n & 2) == 2) sb.append("写 ");
        if( (n & 1) == 1) sb.append("执行 ");
        System.out.println("您的权限为:" + n);
        System.out.println("您具有:" + sb + "的权限");
    }
}
------Output------
您的权限为:5
您具有:读 执行 的权限


4.签到

记录某员工当月哪几天没迟到,或者贴吧某用户哪几天签到了,只须一个int数,32位足够记录31天。

设此数为num,初始值为0。如果员工第N天来上班,那么 

num  |=  1 << N-1

上式等价于num =  num| (1 << (N-1)),根据运算符优先级作了简化





版权声明:本文为博主原创文章,未经博主允许不得转载。

posted @ 2014-12-17 13:05  包清骏  阅读(547)  评论(0编辑  收藏  举报