subtracting binary numbers

Feb 5, 2015 at 12:29am
Hello! i need help with my program. im trying to write a function that takes in 2 binary numbers and subtracts using the carry method. below is what i have so far and it's not outputting anything. i have a feeling that im doing something completely wrong. care to help?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/*
#include <iostream>
#include <string>
using namespace std;

string subtract(string minuend, string subtrahend)
{
	string min = minuend;
	string sub = subtrahend;
	string ans;
	bool carry = false;
	for (int i = min.length() - 1; i >= 0; --i)
	{
		ans[i] = min[i] - sub[i];
		if(carry == true)
		{
			ans[i]-1;
		}
		if (ans[i]==-1)
		{
			ans[i]+2;
			carry = true;
		}
	}
	return ans;
	
}
*/
Feb 5, 2015 at 12:55am
ans[i] = min[i] - sub[i];

"1" - "0" = 1 in integer. then implicit conversion makes ans[i] = " " , space in char


so use to_string()



Feb 5, 2015 at 2:44am
sorry, im not to familiar with to_string(), did you mean something like this?

ans[i] = to_string(min[i] - sub[i]);

or something else?

also thanks for the help!
Feb 5, 2015 at 3:08am
yes.
or, ans[i] = min[i] - sub[i] + int('0');
Feb 5, 2015 at 10:45pm
ok so I did both methods but when i use to_string() it says it's undeclared.

lab06.cpp: In function `std::string subtract(std::string, std::string)':
lab06.cpp:19: error: `to_string' was not declared in this scope
lab06.cpp:19: warning: unused variable 'to_string'
*** Error code 1
make: Fatal error: Command failed for target `lab06.o'

and when i use the other method it doesn't out put anything.

10001000 - 101 =
1000 - 1000 =
1000 - 111 =
1000 - 110 =
1000 - 101 =
1000 - 100 =
1000 - 11 =
1000 - 10 =
1000 - 1 =
1000 - 0 =
0 - 0 =
1111 - 1111 =
1111 - 1110 =
1111 - 1101 =
1111 - 1100 =
1111 - 1011 =
1111 - 1010 =
1111 - 1001 =
1111 - 1000 =
1111 - 111 =
1111 - 110 =
1111 - 101 =
1111 - 100 =
1111 - 11 =
1111 - 10 =
1111 - 1 =
1111 - 0 =

Feb 6, 2015 at 1:11am
to_string() lives in std namespace.
it seems your subtract algorithm is buggy.

i.e. line 14 ans[i] = min[i] - sub[i]; here ans variable is empty. so it's wrong to access [i] s.
Feb 6, 2015 at 1:30am
IMO, the way you are trying will be difficult for you!
it will be little easier and far more applicable to write two functions, one will convert binary string to decimal int, then you do all kind of operations (add,multiply,subtract,divide,power,log etc) on the ints to get the result, then the other function will convert the int result to binary string.

converting algorithm:
http://www.purplemath.com/modules/numbbase.htm
Topic archived. No new replies allowed.