コード例 #1
0
        static void Main(string[] args)
        {
            BinaryNumber add = new BinaryNumber();

            Console.Write("Enter the first number: ");
            int firstNumber = Convert.ToInt32(Console.ReadLine());

            Console.Write("Enter the second number: ");
            int secondNumber = Convert.ToInt32(Console.ReadLine());

            string result = BinaryNumber.AddBinary(firstNumber, secondNumber);

            Console.WriteLine($"{firstNumber} + {secondNumber} = {result}");
        }
コード例 #2
0
        /// <summary>
        /// Add two binary numbers. Throws an exception if the add operation results in overflow.
        /// </summary>
        /// <param name="num1">The first number</param>
        /// <param name="num2">The second number</param>
        /// <returns>The sum of num1 and num2</returns>
        public static BinaryNumber Add(BinaryNumber num1, BinaryNumber num2)
        {
            BinaryNumber result = new BinaryNumber();
            int          carry  = 0;
            int          bitTotal;

            for (int i = sizeInBits - 1; i >= 0; i--)
            {
                bitTotal = carry + num1.bits[i] + num2.bits[i];
                switch (bitTotal)
                {
                case 0:
                    result.mBits[i] = 0;
                    carry           = 0;
                    break;

                case 1:
                    result.mBits[i] = 1;
                    carry           = 0;
                    break;

                case 2:
                    result.mBits[i] = 0;
                    carry           = 1;
                    break;

                case 3:
                    result.mBits[i] = 1;
                    carry           = 1;
                    break;
                }
            }
            if (carry == 1)
            {
                throw new BinaryNumberOverflow("Addition overflow");
            }
            return(result);
        }