位运算和逻辑运算

demo是demonstration  [ˌdemənˈstreɪʃn]的缩写,译为:示范,展示,样片,样稿

 

左移和右移都是对数据在计算机中的补码进行操作
程序执行的时候,操作的是数值的编码表示,比如说负数右移的时候是对它的补码右移,

正数右移后前面缺少的位置全部补0,负数右移后前面缺少的数据全部补1

 

右移运算符>>用来将一个整数的二进制位序列右移若干位,移入的高位添加0,若为负数,移入的高位添加1

 

无符号右移运算符,>>>,也是将一个整数的二进制位序列右移若干位,它与右移运算符的区别是,无论正数还是负数,左边一律移入0,

package computerArea;
public class ComputerArea {
    public static void main(String[] args){
        int i = -100, j = -100, a, b, c, d;
        a = i << 1;
        b = i << 2;
        c = j >> 1;
        d = j >> 2;
        System.out.println("-100左移一位"+a+"\t-100左移两位"+b);
        System.out.println("-100右移一位"+c+"\t-100右移两位"+d);
    }
}

 按位与和按位或当然也是这样啦,都是对数据在计算机中的存储的形式直接进行的操作

package computerArea;
public class ComputerArea {
    public static void main(String[] args){
        int i = 100, j = -10, k, l;
        k = i & j;
        l = i | j;
        System.out.println("100 & -10 = "+k); //输出100
        System.out.println("100 | -10 = "+l); //输出-10
    }
}

 逻辑运算:(“||”是短路或,如果左边是对的,就不执行右边了,同理“&&”是短路与,如果左边是错的,就不执行右边了);而“|” 和“&”左边右边都要执行

package computerArea;
public class ComputerArea {
    public static void main(String[] args){
        int x = 1, y = 2, z = 3;
        boolean u = false;
        System.out.println("u = "+u);
        u = !((x >= --y || y++ < z--) && y == z);
        System.out.println("u = "+u);
        u = !((x >= --y | y++ < z--) & y == z);
        System.out.println("u = "+u);
    }
}
      

 

posted on 2015-10-07 11:57  张明明_1  阅读(415)  评论(0编辑  收藏  举报

导航