I originally wrote this program in Java using the Integer.toBinaryString and then used printwriter to write the results to a file. This program lists all binary combinations in the specified exponent (in this case, 16 bits).
package binary;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
public class BINARY {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try (PrintWriter myFile = new PrintWriter("myThing.txt")) {
for (int i = 0; i < Math.pow(2, 16); i++) { // Iterates over 16 bits
myFile.println(Integer.toBinaryString(i));
}
myFile.close();
} catch (FileNotFoundException ex) {
Logger.getLogger(BINARY.class.getName()).log(Level.SEVERE, null, ex); // standard execption handler added by NetBeans IDE
}
}
}
The program written in C++ is written in much of a similar way, but with a cin << n, where n is the power being raised to the base 2, as C++ requires compilation, so adding an interface allows quicker testing (without the cin << n; construct, performance is very similar).
#include <iostream>
#include <fstream>
#include <bitset>
#include <string>
#include <cmath>
using namespace std;
int binary(int n) {
int remainder, binaryNumber = 0, i = 1, step = 1;
while (n != 0)
{
remainder = n % 2;
//cout << "Step " << step++ << ": " << n << "/2, Remainder = " << remainder << ", Quotient = " << n / 2 << endl;
n /= 2;
binaryNumber += remainder*i;
i *= 10;
}
return binaryNumber;
}
int main()
{
int n;
cout << "Enter the number of bits" << endl;
cin >> n;
cin.ignore();
ofstream myFile;
myFile.open("output64.txt");
cout << "Listing all bit combinations. This may take a while. Please wait." << endl;
for (int i = 0; i < pow(2, n); i++)
{
myFile << binary(i) << "\n";
cout << "Number of iterations = " << i << endl;
}
myFile.close();
}
The program in Java is completes 16 bits in less than a second, usually. However, C++ requires several seconds (10-15) to process all of the binary digits. This doesn't seem to make sense as C++ doesn't need a virtual machine to run bytecode, and is compiled straight into machine code, or at least object code for the operating system to interpret into machine code, so it should be faster, if anything. Anyone have a possible explanation? std::bitset<>() was also used beforehand and acted in a similar way, performance wise. I tried omitting the binary converter and replaced myFile with cout, but the performance doesn't change. Still about ~5000 iterations/sec.