Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binary addition of 2 values represented as strings

I have two strings:

string a = "00001"; /* which is decimal 1 I've converted with next string:
string a = Convert.ToString(2, 2).PadLeft(5, '0'); */
string b = "00010";

I want to perform binary addition between the two so the answer will be 00011 ( 3).

like image 467
Alfred Avatar asked Feb 12 '10 15:02

Alfred


People also ask

How do you represent a string in binary?

To convert a string to binary, we first append the string's individual ASCII values to a list ( l ) using the ord(_string) function. This function gives the ASCII value of the string (i.e., ord(H) = 72 , ord(e) = 101). Then, from the list of ASCII values we can convert them to binary using bin(_integer) .

Can binary represent strings of characters?

Unlike a character string which usually contains text data, a binary string is used to hold non-traditional data such as pictures. The length of a binary string is the number of bytes in the sequence. A binary string has a CCSID of 65535. Only character strings of FOR BIT DATA are compatible with binary strings.

What is binary string example?

Here are some examples: The empty string ε is a binary string. ε is in both Σ* and Σ**. 0 and 1 are finite binary strings, and are in both Σ* and Σ**, as are all finite binary strings.


2 Answers

System.Convert should be able to do the work for you

int number_one = Convert.ToInt32(a, 2);
int number_two = Convert.ToInt32(b, 2);

return Convert.ToString(number_one + number_two, 2);

(you may have to tune the strings a bit)

like image 93
Benoît Vidis Avatar answered Sep 29 '22 02:09

Benoît Vidis


You do it just as you would do it on paper. Start from right and move left. if A[i] + B[i] + carry >= 2, carry remains 1 and you move on. Otherwise, write A[i] + B[i] + carry and set carry to 0.

a = "00001"; b = "00010";

carry = 0; a[4] + b[4] + carry = 1, write 1, set carry = 0: 00001

a[3] + b[3] + carry = 1, write 1, set carry = 0: 00011

And so on.

like image 42
IVlad Avatar answered Sep 29 '22 04:09

IVlad