5 #define MAX_READ_SIZE 80
7 static void crc16ccitt_init(unsigned short *uCcitt16)
12 static void crc16ccitt_update(unsigned short *uCcitt16, unsigned char *pBuffer, unsigned long uBufSize)
17 for(i = 0; i < uBufSize; i++)
21 *uCcitt16 = (*uCcitt16 >> 8) | (*uCcitt16 << 8);
22 *uCcitt16 ^= pBuffer[3-j];
23 *uCcitt16 ^= (*uCcitt16 & 0xFF) >> 4;
24 *uCcitt16 ^= (*uCcitt16 << 8) << 4;
25 *uCcitt16 ^= ((*uCcitt16 & 0xFF) << 4) << 1;
30 static void crc16ccitt_final(unsigned short *uCcitt16)
32 *uCcitt16 = ~(*uCcitt16);
35 void write_file(unsigned short crc, unsigned short file_size, FILE *out, FILE *in)
37 unsigned char buffer[MAX_READ_SIZE];
40 //set file pointer to start of the file
46 size = fread(buffer, sizeof(unsigned char), sizeof(buffer), in);
48 if (size<MAX_READ_SIZE)
68 fwrite(buffer, sizeof(unsigned char), size, out);
71 fwrite(buffer, sizeof(unsigned char), MAX_READ_SIZE, out);
75 fwrite(&crc, sizeof(unsigned char), sizeof(short), out);
76 fwrite(&file_size, sizeof(unsigned char), sizeof(short), out);
82 unsigned short cal_crc(FILE *in)
86 unsigned short crc = 0;
87 unsigned char buffer[MAX_READ_SIZE];
91 crc16ccitt_init(&crc);
95 size = fread(buffer, sizeof(unsigned char), sizeof(buffer), in);
101 buffer[size+1] = 0x0;
102 buffer[size+2] = 0x0;
105 else if ( size%4==2 )
108 buffer[size+1] = 0x0;
111 else if ( size%4==3 )
117 crc16ccitt_update(&crc, (unsigned char*)buffer, size);
119 if (size<MAX_READ_SIZE)
125 crc16ccitt_final(&crc);
126 printf(" ==> output crc 0x%04x with file size 0x%04x\n\r", crc, file_size);
132 int main(int argc, char* argv[])
137 unsigned short crc = 0;
138 unsigned short size = 0;
139 char input_file_name[80];
140 char output_file_name[80];
146 printf("\"imghdr [input_file] [output_file] - calculate the image and prefix to the binary \"!\n\r");
149 strcpy(input_file_name, argv[1]);
150 strcpy(output_file_name, argv[2]);
152 printf("imghdr %s %s!\n\r", input_file_name, output_file_name);
154 if((in = fopen(input_file_name,"rb")) == NULL)
157 if((out = fopen(output_file_name,"wt")) == NULL)
162 fseek( in, 0, SEEK_END );
163 size = ftell(in); // get file length
164 fseek( in, 0, SEEK_SET );
166 printf(" ==> (2) output crc 0x%04x with file size 0x%04x\n\r", crc, size);
167 write_file(crc, size, out, in);