Search code examples
cfortranlfsr

Writing to an unformatted, direct access binary file in C


I'm trying to use this diehard repo to test a stream of numbers for randomness (https://github.com/reubenhwk/diehard). It gives these specifics for the file type it reads:

Then the command diehard will prompt for the name of the file to be tested.

That file must be a form="unformatted",access="direct" binary file of from 10 to 12 million bytes.

These are file conventions specific to fortran, no? The problem is, I'm using a lfsr-generator to generate my random binary stream, and that's in C. I tried just doing fputc of the binary stream to a text file or .bin file, but diehard doesn't seem to be accepting it.

I have no experience with fortran. Is there any way to create this file type using C? Will I just have to bite the bullet and have C call a fortran subroutine that creates the file? Here's my C code for reference:

#include <stdio.h>

int main(void)
{
  FILE *fp;
  fp=fopen("numbers", "wb");

  const unsigned int init = 1;
  unsigned int v = init;
  int counter = 0;

  do {
    v = shift_lfsr(v);
    fputc( (((v & 1) == 0) ? '0' : '1'), fp);
    counter += 1;
  } while (counter < 11000000);
}

Solution

  • You're creating the binary file just fine. Your problem is that you're only writing a single random bit per byte (and expanding it into text). Diehard wants every bit to be random. So accumulate 8 bits at a time before you write:

    do {
      int b = 0;
      for (int i = 0; i < 8; i += 1) {
        v = shift_lfsr(v);
        b <<= 1;
        b |= (v & 1);
      }
      fputc(b, fp);
      . . .