forked from popacai/Frame
-
Notifications
You must be signed in to change notification settings - Fork 0
/
chksum.c
92 lines (82 loc) · 1.67 KB
/
chksum.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include "chksum.h"
#include "crc.h"
#include "common.h"
//We use both checksum and crc here
//Although the function name is chksum.
char* add_chksum(Frame* frame)
{
frame->crc = 0;
frame->nop = 0;
frame->checksum = 0;
//calc the checksum;
char* buf;
buf = convert_frame_to_char(frame);
frame->checksum = calc_checksum(buf);
free(buf);
//calc the crc
buf = convert_frame_to_char(frame);
frame->crc = calc_crc(buf);
free(buf);
buf = convert_frame_to_char(frame);
return buf;
}
unsigned char chksum_all(char* buf)
{
//check for checksum
short checksum;
checksum = calc_checksum(buf);
if (checksum)
{
return 1;
}
//check for crc
unsigned char crc;
crc = calc_crc(buf);
if (crc)
{
return 1;
}
return 0;
}
unsigned char calc_crc(char* buf)
{
unsigned char buffer[MAX_FRAME_SIZE];
unsigned char crc;
memcpy(buffer, buf, MAX_FRAME_SIZE);
crcOp(buffer, MAX_FRAME_SIZE * 8);
crc = buffer[0];
return crc;
}
unsigned short calc_checksum(char* buf)
{
//part length
return chksum((unsigned short *) buf, (MAX_FRAME_SIZE - 2) / 2);
}
unsigned short chksum(unsigned short *buf, int count)
{
register unsigned long sum = 0;
while (count--)
{
sum += *buf++;
if (sum & 0xFFFF0000)
{
sum &= 0xFFFF;
sum++;
}
}
return ~(sum & 0xFFFF);
}
//This is the implementation of chksum
/*
char* add_chksum(Frame* frame)
{
frame->checksum = 0;
char* buf;
buf = convert_frame_to_char(frame);
frame->checksum = chksum(
(unsigned short *) buf, MAX_FRAME_SIZE / 2);
free(buf);
buf = convert_frame_to_char(frame);
return buf;
}
*/