A CRC8 Implementation In C#

So I've tackled  CRC32 CRC16 CRC16-CCITT  (and now  CRC16-CCITT Kermit ) implementations, and found myself wanting a CRC8 class to create checksums for small data (1-2 bytes) sets. Not having ever used or seen CRC8 in use before, I did some reading, and as far as I can tell, I've implemented it correctly... It works anyway, so without further ado, here's my implementation:

public static class Crc8 {
    static byte[] table = new byte[256];
    // x8 + x7 + x6 + x4 + x2 + 1
    const byte poly = 0xd5;

    public static byte ComputeChecksum(params byte[] bytes ) {
        byte crc = 0;
        if ( bytes != null && bytes.Length > 0 ) {
            foreach ( byte b in bytes ) {
                crc = table[crc ^ b];
            }
        }
        return crc;
    } 

    static Crc8( ) {
        for ( int i = 0; i < 256; ++i ) {
            int temp = i;
            for ( int j = 0; j < 8; ++j ) {
                if ( ( temp & 0x80 ) != 0 ) {
                    temp = ( temp << 1 ) ^ poly;
                } else {
                    temp <<= 1;
                }
            }
            table[i] = (byte)temp;
        }
    }
}

This one differs slightly (API wise) from my previous ones, mainly because I was using it for checksum'ing smaller bits of data, so I made the ComputeChecksum method a params argument instead of a first class array type.

Here's a sample of how I was using it (and testing it):
byte crc = Crc8.ComputeChecksum( 1, 2, 3 );
byte check = Crc8.ComputeChecksum( 1, 2, 3, crc );
// here check should equal 0 to show that the checksum is accurate
if ( check != 0 ) {
    Console.WriteLine( "Error in the checksum" );
}

If you have any questions / comments / corrections, post them in the forums


转自:http://www.sanity-free.com/146/crc8_implementation_in_csharp.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值