1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /* **************************************************************************
4 This program creates a CRC checksum and encodes the file that is named
7 Compile with: gcc encode_crc.c -Wall -o encode_crc
9 Author: Michael Margraf (michael.margraf@freecom.com)
10 Copyright: Freecom Technology GmbH, Berlin, 2004
13 ************************************************************************* */
21 // *******************************************************************
22 // CCITT polynom G(x)=x^16+x^12+x^5+1
23 #define POLYNOM 0x1021
25 // CRC algorithm with MSB first
26 int make_crc16(int crc
, char new)
29 crc
= crc
^ (((int)new) << 8);
31 for(i
=0; i
<8; i
++) { // work on 8 bits in "new"
32 crc
<<= 1; // MSBs first
33 if(crc
& 0x10000) crc
^= POLYNOM
;
38 // *******************************************************************
39 // Reads the file "filename" into memory and returns pointer to the buffer.
40 static char *readfile(char *filename
, int *size
)
46 if (stat(filename
,&info
)!=0)
49 if ((fp
=fopen(filename
,"r"))==NULL
)
55 if ((buffer
=(char *)malloc(info
.st_size
+1))==NULL
)
58 if (fread(buffer
,1,info
.st_size
,fp
)!=info
.st_size
)
65 buffer
[info
.st_size
]='\0';
66 if(size
) *size
= info
.st_size
;
77 // *******************************************************************
78 int main(int argc
, char** argv
)
81 printf("ERROR: Argument missing!\n\n");
85 int count
; // size of file in bytes
86 char *p
, *master
= readfile(argv
[1], &count
);
88 printf("ERROR: File not found!\n");
95 for(z
=0; z
<count
; z
++)
96 crc
= make_crc16(crc
, *(p
++)); // calculate CRC
97 short crc16
= (short)crc
;
100 if(argc > 2) { // with flag for device recognition ?
102 for(z=strlen(p); z>0; z--) {
104 *(p++) = (char)crc; // encode device flag
110 for(z
=0; z
<count
; z
++) {
112 *(p
++) = (char)crc
; // encode file
116 // write encoded file...
117 FILE *fp
= fopen(argv
[2], "w");
119 printf("ERROR: File not writeable!\n");
123 if(argc
> 3) { // add flag for device recognition ?
124 fwrite(argv
[3], strlen(argv
[3]), sizeof(char), fp
);
127 // Device is an FSG, so byte swap (IXP4xx is big endian)
128 crc16
= ((crc16
>> 8) & 0xFF) | ((crc16
<< 8) & 0xFF00);
131 fwrite(&crc16
, 1, sizeof(short), fp
); // first write CRC
133 fwrite(master
, count
, sizeof(char), fp
); // write content