summaryrefslogtreecommitdiff
path: root/lib/ultralib/src/io/crc.c
blob: 3293b2d3f674e6d622e1ede41d7c715e8cd33ca3 (plain)
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
#include "PR/os_internal.h"

#if BUILD_VERSION >= VERSION_J

u8 __osContAddressCrc(u16 addr) {
    u32 temp = 0;
    u32 i = 0x400;

    do {
        temp <<= 1;

        if ((u32)addr & i) {
            if (temp & 0x20) {
                temp ^= 0x14;
            } else {
                ++temp;
            }
        } else if (temp & 0x20) {
            temp ^= 0x15;
        }

        i >>= 1;
    } while (i != 0);

    i = 5;

    do {
        temp <<= 1;
        if (temp & 0x20) {
            temp ^= 0x15;
        }
    } while (--i != 0);

    return temp & 0x1F;
}

u8 __osContDataCrc(u8* data) {
    u32 temp = 0;
    u32 i;
    u32 j;

    for (i = 0x20; i; --i) {
        for (j = 0x80; j; j >>= 1) {
            temp <<= 1;

            if ((*data & j) != 0) {
                if ((temp & 0x100) != 0) {
                    temp ^= 0x84;
                } else {
                    ++temp;
                }
            } else if (temp & 0x100) {
                temp ^= 0x85;
            }
        }

        data++;
    }
    do {
        temp <<= 1;

        if (temp & 0x100) {
            temp ^= 0x85;
        }
    } while (++i < 8U);

    return temp;
}

#else

u8 __osContAddressCrc(u16 addr) {
    u8 temp = 0;
    u8 temp2;
    int i;
    
    for (i = 0; i < 16; i++) {
        temp2 = (temp & 0x10) ? 0x15 : 0;

        temp <<= 1;
        temp |= (u8)((addr & 0x400) ? 1 : 0);
        addr <<= 1;
        temp ^= temp2;
    }
    
    return temp & 0x1f;
}

u8 __osContDataCrc(u8 *data) {
    u8 temp = 0;
    u8 temp2;
    int i;
    int j;
    
    for (i = 0; i <= 32; i++) {
        for (j = 7; j > -1; j--) {
            temp2 = (temp & 0x80) ? 0x85 : 0;
            
            temp <<= 1;
            
            if (i == 32) {
                temp &= -1;
            } else {
                temp |= ((*data & (1 << j)) ? 1 : 0);
            }
            
            temp ^= temp2;
        }
        data++;
    }
    return temp;
}

#endif