views:

343

answers:

4

hey guys , im doin a final year project but it has come to a dead end as i dont know any way i can perform binary addition in C#

what i am trying to do is

i have two strings

string a= "00001"; /* which is decimal 1 i made it with the '0's using
 string a = Convert.ToString(2, 2).PadLeft(5, '0'); */
string b= "00010";

what i want to do is perform binary add between the two so the answer will be 00011 ( 3)

it is important that i can perform the addition in this format "00000"

please help me out if u have any ideas as to how this can be achieved

~Alfed

(ps: i was thinking char array but i gave up on the logic behind it :( )

+2  A: 

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.

IVlad
A: 

Very easy -- write a lookup table for 'addition' of binary characters, don't forget to carry if necessary, and send me 50% of the credit you get for the work.

Regards

Mark

High Performance Mark
A: 

I would recommend parsing the data to ints and then adding them, then outputing the result as binary.

C. Ross
+5  A: 

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)

Benoit Vidis
string a = "00001";string b = "00011"; int num1 = Convert.ToInt32(a, 2); int num2 = Convert.ToInt32(b, 2); string ans = Convert.ToString(num1 + num2, 2); MessageBox.Show(ans);"thanks alot :) u have saved my project !!!!!!!!!!!!!!!!"
Alfred
i needed to caluclate attendance using this logic :) ,as 00001 wld represent absent for 1st hour ( we haf hourly wise attendance) so if a student is absent for the next hr in the same day00001 - absent first hr00010 - absent second hr------00011 - absent for 1st and second hr :D it works !! thank u
Alfred
I have to say, I didn't know that particular override of Convert.ToInt32 exists!
Rob