dbx2c.c 1.29 KB
/* dbx2c.c v1 Frank Berndt
 * convert dbx binary fpga code file to C bytes;
 */

#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <fcntl.h>

int
main(int argc, char **argv)
{
	char *cmd;
	char *ifile, *ofile;
	int ifd;
	FILE *ofp;
	int n, m, b;
	u_char in, out;
	u_char buf[8];

	/*
	 * argv[1] is input file;
	 * argv[2] is output file;
	 */
	cmd = argv[0];
	if(argc != 3) {
		fprintf(stderr, "Usage: %s infile outfile\n", cmd);
		exit(1);
	}
	ifile = argv[1];
	ofile = argv[2];

	/*
	 * open binary file;
	 */
	ifd = open(ifile, O_RDONLY);
	if(ifd < 0) {
		fprintf(stderr, "%s: cannot open %s\n", cmd, ifile);
		exit(2);
	}
	/*
	 * open output file;
	 */
	ofp = fopen(ofile, "w");
	if( !ofp) {
		fprintf(stderr, "%s: cannot open %s\n", cmd, ofile);
		exit(3);
	}
	fprintf(ofp, "/* file generated by dbx2c */\n");

	/*
	 * convert binary to C-style chars;
	 * flip bits as xilinx DO is MSB;
	 */
	while(1) {
		n = read(ifd, buf, sizeof(buf));
		if(n < 0)
			fprintf(stderr, "%s: %s read error\n", cmd, ifile);
		if(n <= 0)
			break;
		fprintf(ofp, "\t");
		for(m = 0; m < n; m++) {
			in = buf[m];
			out = 0;
			for(b = 0; b < 8; b++) {
				out <<= 1;
				out |= (in & 1);
				in >>= 1;
			}
			fprintf(ofp, "0x%02x,", out);
		}
		fprintf(ofp, "\n");
	}
	close(ifd);
	fclose(ofp);
	return(0);
}