Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
How to find the Sum of two Binary Numbers using C#?
To find the sum of two binary numbers, firstly set them.
val1 = 11110; val2 = 11100;
Now call the displaySum() method, which created to display the sumL.
sum = displaySum(val1, val2);
We have set a new array in the method to display each bit of the binary number.
long[] sum = new long[30];
Now let us see the complete code to calculate the sum of binary numbers as shown in the code below −
Example
using System;
class Demo {
public static void Main(string[] args) {
long val1, val2, sum = 0;
val1 = 11110;
val2 = 11100;
Console.WriteLine("Binary one: "+val1);
Console.WriteLine("Binary two: "+val2);
sum = displaySum(val1, val2);
Console.WriteLine("Sum = {0}", sum);
}
static long displaySum (long val1, long val2) {
long i = 0, rem = 0, res = 0;
long[] sum = new long[30];
while (val1 != 0 || val2 != 0) {
sum[i++] =(val1 % 10 + val2 % 10 + rem) % 2;
rem =(val1 % 10 + val2 % 10 + rem) / 2;
val1 = val1 / 10;
val2 = val2 / 10;
}
if (rem != 0)
sum[i++] = rem;
i = i-1;
while (i >= 0)
res = res * 10 + sum[i--];
return res;
}
}
Output
Binary one: 11110 Binary two: 11100 Sum = 111010
Advertisements
