111,092
社区成员




public class CRC16
{
struct B
{
public byte lo;
public byte hi;
}
[System.Runtime.InteropServices.StructLayout(LayoutKind.Explicit)]
struct w2b
{
[FieldOffset(0)]
public ushort w;
[FieldOffset(0)]
public B b;
}
public ushort CRC16(byte[] buf, byte len)
{
w2b crc16;
byte i, j, p = 0;
ushort poly = 0xa001;
crc16.b.lo = 0x00;
crc16.w = 0xffff;
while (len-- > 0)
{
crc16.b.lo ^= buf[p++];
for (i = 0; i < 8; i++)
{
j = (byte)(crc16.b.lo & 0x01);
crc16.w >>= 1;
if (j > 0)
crc16.w ^= poly;
}
}
return crc16.w;
}
}
unsafe ushort CRC16(byte *buf, byte len)
{
w2b CRC16;
byte i,j;
ushort poly = 0xa001;
CRC16.w = 0xffff;
CRC16.b = new B();
while((len--)!=0)
{
CRC16.b.lo ^= *buf++;
for (i = 0; i < 8; i++)
{
j =(byte) (CRC16.b.lo & 0x01);
CRC16.w >>= 1;
if (j!=0) CRC16.w ^= poly;
};
};
return CRC16.w;
}
// 没测试,感觉应该差不多
struct B
{
public byte lo;
public byte hi;
}
struct w2b
{
public ushort w;
public B b;
}
struct s2b
{
public ushort w;
public B b;
}
ushort CRC16(byte[] buf, byte len)
{
w2b crc16;
byte i, j, p = 0;
ushort poly = 0xa001;
crc16.w = 0xffff;
while (len-- > 0)
{
crc16.b.lo ^= buf[p++];
for (i = 0; i < 8; i++)
{
j = (byte)(crc16.b.lo & 0x01);
crc16.w >>= 1;
if (j > 0) crc16.w ^= poly;
}
}
return crc16.w;
}