1 /* **************************************************************************
3 This program creates a CRC checksum and encodes the file that is named
6 Compile with: gcc encode_crc.c -Wall -o encode_crc
8 Author: Michael Margraf (michael.margraf@freecom.com)
9 Copyright: Freecom Technology GmbH, Berlin, 2004
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 2 of the License, or
15 (at your option) any later version.
17 This program is distributed in the hope that it will be useful,
18 but WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
20 General Public License for more details.
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 ************************************************************************* */
34 // *******************************************************************
35 // CCITT polynom G(x)=x^16+x^12+x^5+1
36 #define POLYNOM 0x1021
38 // CRC algorithm with MSB first
39 int make_crc16(int crc, char new)
42 crc = crc ^ (((int)new) << 8);
44 for(i=0; i<8; i++) { // work on 8 bits in "new"
45 crc <<= 1; // MSBs first
46 if(crc & 0x10000) crc ^= POLYNOM;
51 // *******************************************************************
52 // Reads the file "filename" into memory and returns pointer to the buffer.
53 static char *readfile(char *filename, int *size)
59 if (stat(filename,&info)!=0)
62 if ((fp=fopen(filename,"r"))==NULL)
68 if ((buffer=(char *)malloc(info.st_size+1))==NULL)
71 if (fread(buffer,1,info.st_size,fp)!=info.st_size)
78 buffer[info.st_size]='\0';
79 if(size) *size = info.st_size;
90 // *******************************************************************
91 int main(int argc, char** argv)
94 printf("ERROR: Argument missing!\n\n");
98 int count; // size of file in bytes
99 char *p, *master = readfile(argv[1], &count);
101 printf("ERROR: File not found!\n");
108 for(z=0; z<count; z++)
109 crc = make_crc16(crc, *(p++)); // calculate CRC
110 short crc16 = (short)crc;
113 if(argc > 2) { // with flag for device recognition ?
115 for(z=strlen(p); z>0; z--) {
117 *(p++) = (char)crc; // encode device flag
123 for(z=0; z<count; z++) {
125 *(p++) = (char)crc; // encode file
129 // write encoded file...
130 FILE *fp = fopen(argv[2], "w");
132 printf("ERROR: File not writeable!\n");
136 if(argc > 3) { // add flag for device recognition ?
137 fwrite(argv[3], strlen(argv[3]), sizeof(char), fp);
140 // Device is an FSG, so byte swap (IXP4xx is big endian)
141 crc16 = ((crc16 >> 8) & 0xFF) | ((crc16 << 8) & 0xFF00);
144 fwrite(&crc16, 1, sizeof(short), fp); // first write CRC
146 fwrite(master, count, sizeof(char), fp); // write content