This should multiply n1.txt with n2.txt and write the result to n3.txt. Both input numbers can be any length. Characters other than 0 and 1 will be ignored. It's quick and dirty but seems to work. I didn't bother cutting off leading zeros though.
Code:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
void read_number(std::string const &file, std::vector<bool> &num) {
std::ifstream in(file.c_str());
num.reserve(100);
while (in.good()) {
int v = in.get();
if (v == (int)'0') num.push_back(false);
else if (v == (int)'1') num.push_back(true);
}
}
void write_number(std::string const &file, std::vector<bool> const &num) {
std::ofstream out(file.c_str());
for (std::vector<bool>::const_iterator it = num.begin(); it != num.end(); it++) out << (*it ? '1' : '0');
out << std::endl;
}
void multiply(std::vector<bool> const &num1, std::vector<bool> const &num2, std::vector<bool> &num3) {
size_t s1 = num1.size();
size_t s2 = num2.size();
num3.resize(s1 + s2);
for (size_t i1 = s1 - 1; i1 < s1; i1--) {
if (num1[i1]) {
size_t i3 = s2 + i1;
bool c = false;
for (size_t i2 = s2 - 1; i2 < s2; i2--) {
bool o1 = num2[i2];
bool o2 = num3[i3];
num3[i3--] = o1 ^ o2 ^ c;
c = o1 & o2;
}
}
}
}
int main() {
std::vector<bool> n1, n2, n3;
read_number("n1.txt", n1);
read_number("n2.txt", n2);
multiply(n1, n2, n3);
write_number("n3.txt", n3);
return 0;
}
Example:
Originally Posted by
n1.txt
1100
Originally Posted by
n2.txt
1010
Originally Posted by
n3.txt
01111000
Have fun!
Bookmarks