二进制操作

二进制操作

public class BitOperationTest {

    /**
     * 或运算
     */
    private static void testHuo(){
        /*
         * 真真为真,真假为真 假假为假
         * 0000 0001
         * 0000 0101
         * ----------
         * 0000 0101
         * ----------
         * 5           结果
         */
        System.out.println("或:"+(1|5));
    }

    /**
     * 与运算
     */
    private static void testYu(){
        /*
         * 真真为真 其他为假
         * 0000 0001
         * 0000 0101
         * ----------
         * 0000 0001
         * -----------
         * 1          结果
         */
        System.out.println("与:"+(1&5));
    }

    /**
     * 异或运算
     */
    private static void testYiHuo(){
        /*
         * 真真为假 假假为假 真假为真
         * 0000 0001
         * 0000 0101
         * ----------
         * 0000 0100
         * ----------------
         * 4              结果
         */
        System.out.println("异或"+(1^5));
    }

    /**
     * 取反运算
     */
    private static void testQuFan(){
        /*
         * 真真为假 假假为假 真假为真
         *
         * 0000 0101
         * ----------
         * 1111 1010
         * ----------
         * 0000 0101          补码+1
         * ----------------
         *  -6               结果
         */
        System.out.println(""+(~5));
    }

    /**
     * 无符号左移
     */
    private static void testLeftMove(){
        /*
        * 0000 0101
        * ---------
        * 0001 0100 左移
        * -------------
        * 20        结果
        * */
        System.out.println(5 << 2);
    }

    /**
     * 无符号右移
     */
    private static void testRightMove(){
        /*
         * 0000 0101
         * ---------
         * 0000 0001 右移
         * -------------
         * 1        结果
         * */
        System.out.println(5 >> 2);
    }

    /**
     * 带符号左移
     */
    private static void testLeftMoveWithFh(){
        /*
         * 1111 1011
         * ---------
         * 1110 1100    左移
         * -------------
         * 0001 0011 补码 +1
         * -------------------
         * 0001 0100
         * ---------------
         * -20        结果
         * */
        System.out.println(-5 << 2);
    }

    /**
     * 带符号右移
     */
    private static void testRightMoveWithFh(){
        /*
         * 1111 1011
         * ---------
         * 1111 1110 右移
         * -------------
         * -2        结果
         * */
        System.out.println(-5 >> 2);
    }

    public static void main(String[] args) {
        testHuo();
        testYu();
        testYiHuo();
        testQuFan();
        testLeftMove();
        testRightMove();
        testRightMoveWithFh();
        testLeftMoveWithFh();
        System.out.println(256 >>> 2);
    }
}

你可能感兴趣的:(学习笔记)