Click here to Skip to main content
15,886,761 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi guys, I'm kinda new to programming, currently self studying C# GUI atm.
How do I do binary subtraction and multiplication without using padleft method?
I managed to do the binary addition part and was told that I can reuse the addition code for multiplication.

NVM solved.
Posted
Updated 4-Sep-14 6:49am
v3

First off, that is some odd code you have there:
C#
for (int i = textBox1.TextLength - 1; i < textBox2.TextLength - 1; i++)
{ num1 = "0" + textBox1.Text; }
What does that do?
It's the same as:
Since the code inside the loop doesn't use the loop variable i, or change anythign other than the num1 value, it's the same as not having a loop at all - it just loads teh same value into num1 several times...

I can see what you are trying to do, sort of - but assuming that each character in num1 is zero or one (or it isn't binary) how can the result ever be three?
0 + 0 == 0
0 + 1 == 1
1 + 0 == 1
1 + 1 == 2
So the testing in your main processing loop is...um...odd.

I'd sort that out before you try to get to multiplication! :laugh:

[edit]Ignore that: I forgot the carry! :O [/edit]

So, the inner loop will work - so multiplication is pretty easy:
Think how you were taught to do multiplication:
7 * 5 == 7 + 7 + 7 + 7 + 7

Then for more advanced users there is long mutiplication:
123
*45
---
4920
+615
----
5535
 
Share this answer
 
v2
Comments
OriginalGriff 4-Sep-14 11:18am    
Except...does it work?
Did you try it?
T1 = 1010101
T2 = 11
Should give you
N1 = 1010101
N2 = 0000011
But does it when you try?
This will convert your two binary strings to integers, you can then subtract, and return it converted back to a binary string

C#
int i = Convert.ToInt32(textBox1.Text, 2);
int j = Convert.ToInt32(textBox2.Text, 2);
Return Convert.ToString(i - j, 2);
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900