Write a function Add() that returns sum of two integers. Sum of two bits can be obtained by performing XOR (^) of the two bits. Carry bit can be obtained by performing AND (&) of two bits.
This example is a fine example to understand bitwise operators.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
class Program { static void Main() { int num1, num2; Console.Write("\nEnter the Number 1 : "); num1 = Convert.ToInt32(Console.ReadLine()); Console.Write("\nEnter the Number 2 : "); num2 = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("\nAddition of two num is : {0}", add(num1, num2)); Console.ReadLine(); } static int add(int a, int b) { int result = 0, carry; carry = a & b; if (Convert.ToBoolean(carry)) { result = a ^ b; carry = carry << 1; result = add(carry, result); } else { result = a ^ b; } return result; } } |
You can find more similar examples of programming for this programming language in the site.