Use Java binary operation, displacement operation, logical operation

1. For signed data
Signed number: the first (highest) number (1 means negative number, 0 means positive number) source
code complement code

Positive number: source code, inverse code and complement code are all the same Zero :     source
code, inverse code and complement code are     all 0 >0)     Complement code: Inverse code +1



When the computer is running, it is calculated in the way of complement number
2. Relational operators
>,<,
>=,<=,
==, !=
judge the result as Boolean type
3. Logical operators and displacement operations

And &, or |, exclusive or ^, negation~

Below is the code written in Java

package com.demo;

import java.sql.SQLOutput;

/**
 * 位移运算 右移给最高位加0,然后删除最右边多余的0
 * 位移运算 左移给最高位减0,然后给最右边空出的位置补0
 */
public class CalculationTest {
    public static void main(String[] args) {
//        System.out.println(32>>1);//右移1位相当32缩小2的1次方倍
//        System.out.println(32>>2);//右移2位相当32缩小2的2次方倍
//        System.out.println(32<<1);//左移1位相当32的扩大1次方倍
//        System.out.println(32<<2);//左移2位相当32的扩大2次方倍
        ConvertBinary(3);
        and(5, 12);//逻辑位与运算  1&1=1,1&0=0,0&0=0,同为1才是1
        or(5, 12);//逻辑位或运算  1|1=1,1|0=1,0|0=0,有1就为1,同时为0才是0
        xor(7, 11);//逻辑位异或运算 1^1=0,1^0=1,0^1=1,0^0=0 同为0,异为1


    }

    /**
     * Convert any number to binary
     */
    public static void ConvertBinary(int anyNum) {
        System.out.println("十进制数字" + anyNum + "换算成二进制:" + Integer.toBinaryString(anyNum));
        System.out.println("把" + anyNum + "右移1位得到十进制:" + (anyNum >> 1) + "二进制结果:" + Integer.toBinaryString(anyNum >> 1));
        System.out.println("把" + anyNum + "左移1位得到十进制:" + (anyNum << 1) + "二进制结果:" + Integer.toBinaryString(anyNum << 1));
    }

    public static void and(int firtNum, int secondNum) {
        int a = firtNum;
        System.out.println(a + "二进制结果:" + Integer.toBinaryString(a));
        int b = secondNum;
        System.out.println(b + "二进制结果:" + Integer.toBinaryString(b));
        int c = a & b;
        System.out.println(a + "&" + b + "=" + c + "再转成二进制结果为:" + Integer.toBinaryString(c));
    }

    public static void or(int firtNum, int secondNum) {
        int a = firtNum;
        System.out.println(a + "二进制结果:" + Integer.toBinaryString(a));
        int b = secondNum;
        System.out.println(b + "二进制结果:" + Integer.toBinaryString(b));
        int c = a | b;
        System.out.println(a + "|" + b + "=" + c + "再转成二进制结果为:" + Integer.toBinaryString(c));

    }

    public static void xor(int firtNum, int secondNum) {
        int a = firtNum;
        System.out.println(a + "二进制结果:" + Integer.toBinaryString(a));
        int b = secondNum;
        System.out.println(b + "二进制结果:" + Integer.toBinaryString(b));
        int c = a ^ b;
        System.out.println(a + "^" + b + "=" + c + "再转成二进制结果为:" + Integer.toBinaryString(c));
    }
}

Guess you like

Origin blog.csdn.net/m0_49128301/article/details/131493936