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).
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) .
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.
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.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With