0

I am trying to write a file that outputs every possible 16 bit number. I am getting the output in 16 digit hex instead of 16 digit binary. How can I get it in binary. Thank you

FILE * file = fopen("16BitFile.txt", "w"); 
for(int i=0; i<65536; i++) 
{ 
    fprintf(file, "%016x\n", i); 
}
  • You might find [`std::bitset`](http://en.cppreference.com/w/cpp/utility/bitset) may save you some work of having to roll your own translation code. – WhozCraig Oct 18 '13 at 20:23
  • 1
    And the bitset solution is detailed in the response to http://stackoverflow.com/questions/7349689/c-how-to-print-using-cout-the-way-a-number-is-stored-in-memory – Trevor Tippins Oct 18 '13 at 20:23

2 Answers2

1
std::ifstream ifs ("16BitFile.txt", std::ifstream::in);
int number;
ifs>>number;
std::bitset<16> x(number);
std::cout<<x;

you can check this for more information about how to print integers using bitset

4pie0
  • 29,204
  • 9
  • 82
  • 118
0
#include <stdio.h>
#include <stdexcept>
#include <stdint.h>

int main()
{
  FILE * file = fopen("16BitFile.txt", "wb");
  int16_t i = 0;
  for (;;) {
    if (fwrite(&i, sizeof(i), 1, file) != 1)
      throw std::runtime_error("fwrite failed");
    if (++i == 0)
      break;
  }
  if (fclose(file) != 0)
    throw std::runtime_error("fclose failed");
}
Waxrat
  • 2,075
  • 15
  • 13