Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- * Demonstrates how the incorrect check value of 0x29B1 may be reported for the test string
- * "123456789" when it should be 0xE5CC.
- */
- #include <stdio.h>
- #include <string.h>
- #define poly 0x1021 /* crc-ccitt mask */
- /* Global variables */
- int off = 0;
- char text[1000];
- unsigned short good_crc = 0;
- unsigned short bad_crc = 0;
- unsigned short text_length = 750;
- void go(void);
- void repeat_character(unsigned char, unsigned short);
- void update_good_crc(unsigned short);
- void augment_message_for_good_crc(void);
- void update_bad_crc(unsigned short);
- int
- main(int argc, char **argv)
- {
- FILE *f = fopen(argv[1], "r");
- printf("%d bytes read\n", fread(text, 1, 752, f));
- fclose(f);
- go();
- printf("Good_CRC = %04X, Bad_CRC = %04X, Length = %u\n", good_crc, bad_crc, text_length);
- text[750] = (good_crc & 0xFF00) >> 8;
- text[751] = (good_crc & 0x00FF);
- f = fopen(argv[1], "w");
- printf("%d bytes written\n", fwrite(text, 1, 752, f));
- fclose(f);
- return 0;
- }
- void
- go(void)
- {
- int i;
- unsigned short ch;
- for (i = 0; i < (text_length - off); i++) {
- update_good_crc(text[i + off]);
- update_bad_crc(text[i + off]);
- }
- augment_message_for_good_crc();
- }
- void
- repeat_character(unsigned char ch, unsigned short n)
- {
- unsigned short i;
- for (i = 0; i < n; i++)
- text[i] = ch;
- text[n] = 0;
- }
- void
- update_good_crc(unsigned short ch)
- {
- unsigned short i, v, xor_flag;
- /* Align test bit with leftmost bit of the message byte. */
- v = 0x80;
- for (i = 0; i < 8; i++) {
- if (good_crc & 0x8000)
- xor_flag = 1;
- else
- xor_flag = 0;
- good_crc <<= 1;
- if (ch & v)
- /*
- * Append next bit of message to end of CRC if it is not zero. The zero bit
- * placed there by the shift above need not be changed if the next bit of
- * the message is zero.
- */
- good_crc++;
- if (xor_flag)
- good_crc ^= poly;
- /* Align test bit with next bit of the message byte. */
- v >>= 1;
- }
- }
- void
- augment_message_for_good_crc(void)
- {
- unsigned short i, xor_flag;
- for (i = 0; i < 16; i++) {
- if (good_crc & 0x8000)
- xor_flag = 1;
- else
- xor_flag = 0;
- good_crc <<= 1;
- if (xor_flag)
- good_crc ^= poly;
- }
- }
- void
- update_bad_crc(unsigned short ch)
- {
- /*
- * Based on code found at
- * http://www.programmingparadise.com/utility/crc.html
- */
- unsigned short i, xor_flag;
- /*
- * Why are they shifting this byte left by 8 bits??
- * How do the low bits of the poly ever see it?
- */
- ch <<= 8;
- for (i = 0; i < 8; i++) {
- if ((bad_crc ^ ch) & 0x8000)
- xor_flag = 1;
- else
- xor_flag = 0;
- bad_crc <<= 1;
- if (xor_flag)
- bad_crc ^= poly;
- ch <<= 1;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement