JAVA 模拟逻辑门实现加法运算( 半加法器 + 全加法器 )

硬件懒得花钱买板子,《我的世界》又不会玩,于是用 java 模拟了一下,算是加深理解和记忆吧!

参考资料:

JAVA 模拟逻辑门实现加法运算( 半加法器 + 全加法器 )_第1张图片

JAVA 模拟逻辑门实现加法运算( 半加法器 + 全加法器 )_第2张图片

JAVA 模拟逻辑门实现加法运算( 半加法器 + 全加法器 )_第3张图片

 

java代码:

import lombok.Getter;
import lombok.Setter;

public class Test {
    
    public static void main(String[] args)throws Exception{
        System.out.println( myAdd( 52423523,2356346 ) );
    }

    /**
     * 半加器
     * @param n1 加数1
     * @param n2 加数2
     * @return
     * @throws Exception
     */
    public static MyResult halfAdder( int n1,int n2 )throws Exception{
        if( ( ( n1 < 0 ) || ( n1 > 1 ) )  || ( ( n2 < 0 ) || ( n2 > 1 ) ) ){
            throw new Exception( "unsupported parametrers for halfAdder!" );
        }
        int sum = n1 ^ n2; // "异或运算" 计算出 "和( 也称本位 )"
        int carryOutput = n1 & n2; // "与运算" 计算出 "进位( 输出 )"
        return new MyResult( sum,carryOutput );
    }

    public static int myAdd( int n1,int n2 ) throws Exception {
        String binaryString1 = Integer.toBinaryString(n1);
        String binaryString2 = Integer.toBinaryString(n2);
        System.out.println( "调整长度之前:" );
        System.out.println( "binaryString1 = " + binaryString1 );
        System.out.println( "binaryString2 = " + binaryString2 );
        if( binaryString1.length() < binaryString2.length() ){
            int diffLen = binaryString2.length() - binaryString1.length();
            for( int i=0;i=0;i-- ){
            int a= binaryString1.charAt( i ) - 48;
            int b= binaryString2.charAt( i ) - 48;
            MyResult myResult = fullAdder(a, b, carryInput);
            int sum = myResult.getSum();
            s = sum + s;
            carryInput = myResult.getCarryOutput();
            System.out.println( a +" + " + b + "   和=" + sum + ",进位=" + carryInput );
        }
        int finalCarryOutput = carryInput;
        s=finalCarryOutput +s;
        System.out.println("s=" + s);
        return Integer.valueOf( s,2 );
    }

    /**
     * 全加器
     * @param n1 加数1
     * @param n2 加数2
     * @param carryInput 进位( 输入 )
     * @return
     * @throws Exception
     */
    public static MyResult fullAdder( int n1,int n2,int carryInput )throws Exception{
        // 对应图中黄色的半加法器
        MyResult myResultYellow = halfAdder(n1, n2);

        // 对应图中绿色的半加法器
        MyResult myResultGreen = halfAdder(myResultYellow.getSum(), carryInput);

        int sum = myResultGreen.getSum();
        int carryOuput = myResultYellow.getCarryOutput() | myResultGreen.getCarryOutput(); // 或运算

        return new MyResult( sum,carryOuput );
    }


    @Getter
    @Setter
    public static class MyResult{

        private Integer sum;//和( 也称本位 )
        private Integer carryOutput;//进位( 输出 )

        public MyResult(Integer sum, Integer carryOutput) {
            this.sum = sum;
            this.carryOutput = carryOutput;
        }
    }

}

 

你可能感兴趣的:(算法,JAVA,java,算法)