2 changed files with 57 additions and 0 deletions
@ -0,0 +1,54 @@ |
|||||
|
using System; |
||||
|
using System.Collections.Generic; |
||||
|
using System.Text; |
||||
|
|
||||
|
namespace Apewer.Internals |
||||
|
{ |
||||
|
|
||||
|
class CRC16 |
||||
|
{ |
||||
|
|
||||
|
public static CRC16 Instance = new CRC16(); |
||||
|
|
||||
|
const ushort origin = 0xFFFF; |
||||
|
const ushort polynomial = 0xA001; |
||||
|
|
||||
|
ushort[] table = new ushort[256]; |
||||
|
|
||||
|
public CRC16() |
||||
|
{ |
||||
|
ushort value, temp; |
||||
|
for (ushort i = 0; i < table.Length; ++i) |
||||
|
{ |
||||
|
value = 0; |
||||
|
temp = i; |
||||
|
for (byte j = 0; j < 8; ++j) |
||||
|
{ |
||||
|
if (((value ^ temp) & 0x0001) != 0) |
||||
|
{ |
||||
|
value = (ushort)((value >> 1) ^ polynomial); |
||||
|
} |
||||
|
else |
||||
|
{ |
||||
|
value >>= 1; |
||||
|
} |
||||
|
temp >>= 1; |
||||
|
} |
||||
|
table[i] = value; |
||||
|
} |
||||
|
} |
||||
|
|
||||
|
public ushort Compute(byte[] bytes) |
||||
|
{ |
||||
|
ushort crc = origin; |
||||
|
for (int i = 0; i < bytes.Length; ++i) |
||||
|
{ |
||||
|
byte index = (byte)(crc ^ bytes[i]); |
||||
|
crc = (ushort)((crc >> 8) ^ table[index]); |
||||
|
} |
||||
|
return crc; |
||||
|
} |
||||
|
|
||||
|
} |
||||
|
|
||||
|
} |
Loading…
Reference in new issue