mifwrite.cpp

mifwrite reads a binary file and generates an Altera memory initialization file (.mif).

Usage

	usage: mifwrite input_file output_file [offset]
	The default offset is zero
For example, if we generate a binary file a.bin and we know that the desired entry point is located at 0x40 relative to the start of the file, then we would enter the command:
       mifwrite a.out a.mif 40


#include <stdio.h>

void mifwrite(FILE *in, FILE *out, int offset);

int main(int argc, char *argv[])
{
	char *filename;

	if (argc<3) {
		printf("usage: mifwrite input_file output_file [offset]\n");
		printf("The default offset is zero");
		return -1;
	}

	FILE *in, *out;
	errno_t err;
	filename = argv[1];
	err = fopen_s(&in,filename,"rb");
	if (err) {
		printf("file: %s not found\n",filename);
		return -1;
	}
	filename = argv[2];
	err = fopen_s(&out,filename,"wt");
	if (err) {
		printf("file: %s not opened\n",filename);
		return -1;
	}
	int offset = 0;
	if (argc>3) sscanf_s(argv[3],"%x",&offset);
	if (offset) printf("address_offset %x\n",offset);
	mifwrite(in,out,offset);
	return 0;
}

void mifwrite(FILE *in, FILE *out,int offset)
{
	int count;
	unsigned int data;
	unsigned int address = 0;
	int ndepth = 256;
	int nwidth = 32;
	fprintf(out,"DEPTH = %d;\n",ndepth);
	fprintf(out,"WIDTH = %d;\n\n",nwidth);
	fprintf(out,"ADDRESS_RADIX = HEX;\n");
	fprintf(out,"DATA_RADIX = HEX;\n");
	fprintf(out,"CONTENTS\n  BEGIN\n");
	fprintf(out,"[0..%x]   :  0;\n",ndepth-1);
	address = 0;
	offset = offset>>2;
	while (count = fread(&data,4,1,in)) {
		if (address<offset) {
			offset--;
			continue;
		}
		fprintf(out,"%04x  : %08x;\n",address,data);
		address++;
		if (address>=ndepth) break;
	}
	fprintf(out,"END;\n");
	fclose(in);
	fclose(out);
}


Maintained by John Loomis, updated Tue Jul 10 13:44:08 2007