PS2SDK
PS2 Homebrew Libraries
Loading...
Searching...
No Matches
crc16.c
1#include "crc16.h"
2
3
4uint16_t crc16(void *buf, int len)
5{
6 uint16_t *bf = buf;
7 uint32_t poly = 0; // Initializing poly to 0 AND using it as initializer in the loop for polyIn results in the compiler forcing it always to 0 in the loop (so don't use variables as initializers - i.e. u32 polyIn = poly; ).
8 int i;
9 len /= 2; // to u16
10 for (i = 0; i < len; i++) {
11 uint32_t polyIn, di;
12
13 di = (((bf[i]) << 8) & 0xFF00) | (((bf[i]) >> 8) & 0xFF);
14 polyIn = poly;
15 // PPC has an instruction for shifting and masking (continuous mask) at the same time.
16 // This sequence must be folowed because some of the bits altered in the first operations are used in the folowing.
17 polyIn ^= ((polyIn ^ di) >> 4) & 0x0F00;
18 polyIn ^= ((polyIn ^ di) >> 4) & 0x00F0;
19 polyIn ^= ((polyIn ^ di) >> 11) & 0x001F;
20 polyIn ^= ((polyIn ^ di) >> 4) & 0x000F;
21 polyIn ^= di;
22 poly = polyIn ^ (polyIn << 5) ^ (polyIn << 12);
23 }
24
25 uint16_t crc = poly;
26 return crc;
27}