-
Notifications
You must be signed in to change notification settings - Fork 0
/
CRC.h
119 lines (96 loc) · 2.08 KB
/
CRC.h
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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
///////////////////////////////////////////////////////////
//
// SuperDiskIndex
//
////////////////////
//
//
//
#pragma once
#include "Helpers.h"
template <class T> class CRC_XOR
{
public:
CRC_XOR(T initval) : State(initval) {}
~CRC_XOR() {}
////// Inputs
// feed single values (stream mode)
void Feed(T value, bool swap_endian)
{
if (swap_endian)
{
State ^= swap(value);
} else {
State ^= value;
}
}
// feed buffer of data (block mode)
// Note: count is a count of words, dependent on crc size!
void Block(void *ptr, u32 count, bool swap_endian)
{
T *p = (T *)ptr;
for (u32 i=0; i<count; i++)
{
if (swap_endian)
{
State ^= swap(p[i]);
} else {
State ^= p[i];
}
}
}
////// Outputs
// Query last state for comparison
T Get() { return State; }
// Check whether state is zero
bool Check() { return State==0; }
protected:
T State;
};
typedef CRC_XOR<u8> CRC8_xor;
typedef CRC_XOR<u16> CRC16_xor;
typedef CRC_XOR<u32> CRC32_xor;
///////////////////////////////////////////////////////////////
template <class T> class CRC_CCITT
{
public:
CRC_CCITT(T initval) : State(initval) {}
~CRC_CCITT() {}
////// Inputs
// feed single values (stream mode)
void Feed(T value, bool swap_endian, int force_input_width=0)
{
T input = swap_endian?swap(value):value;
int bitsize = sizeof(T)*8;
for (int i=(force_input_width>0?(force_input_width-1):(bitsize-1)); i>=0; i--)
{
FeedBit((input>>i)&0x1);
}
}
// feed buffer of data (block mode)
// Note: count is a count of words, dependent on crc size!
void Block(void *ptr, u32 count, bool swap_endian)
{
T *p = (T *)ptr;
for (u32 i=0; i<count; i++)
{
Feed(p[i],swap_endian);
}
}
void FeedBit(u8 bit)
{
int bitsize = sizeof(T)*8;
u8 f = bit^(State>>(bitsize-1));
T fbits = (f<<5)|(f<<12)|(f<<0);
State = (State<<1) ^ fbits;
}
////// Outputs
// Query last state for comparison
T Get() { return State; }
// Check whether state is zero
bool Check() { return State==0; }
protected:
T State;
};
typedef CRC_CCITT<u16> CRC16_ccitt;
typedef CRC_CCITT<u32> CRC32_ccitt;