2010-11-15 64 views
1

我需要将这些C函数转换为C#。只是想仔细检查一下我是否做得对。谢谢!CRC功能。将C转换为C#

C代码:

unsigned short Crc; 

unsigned short update_crc(unsigned short crc, char c) { 
    char i; 

    crc ^= (unsigned short)c<<8; 
    for (i=0; i<8; i++) { 
     if (crc & 0x8000) crc = (crc<<1)^0x1021; 
     else crc <<=1; 
    } 
    return crc; 
} 


void exampleCRC(void){ 

#define INITIAL_CRC 0xffff 

unsigned short Crc = INITIAL_CRC; 
record_t record; 

    for (byteCount=0; byteCount<sizeof(record_t); byteCount++) { 
     Crc = update_crc(Crc, record[byteCount]); 
    } 
} 

C#代码:

ushort UpdateCrc(ref ushort crc, byte b) 
{ 
    crc ^= (ushort)(b << 8); 

    for (int i = 0; i < 8; i++) 
    { 
     if ((crc & 0x8000) > 0) 
      crc = (ushort)((crc << 1)^0x1021); 
     else 
      crc <<= 1; 
    } 

    return crc; 
} 

ushort CalcCrc(byte[] data) 
{ 
    ushort crc = 0xFFFF; 

    for (int i = 0; i < data.Length; i++) 
     crc = UpdateCrc(ref crc, data[i]); 

    return crc; 
} 
+0

两个字:单元测试! – vcsjones 2010-11-15 03:46:45

+0

是的,好主意。谢谢! – Matt 2010-11-15 03:52:32

回答

3

似乎没什么问题,除非你真的因为你返回不需要为UpdateCrc一个ref参数无论如何,修改后的值。

+0

好的。感谢那! – Matt 2010-11-15 03:51:51

0

您是否尝试过在各种不同的值上运行测试?

也可能让他们static职能(如果这不是你的计划已经),因为他们似乎不需要访问任何对象状态。

+0

听起来不错。谢谢! – Matt 2010-11-15 03:51:23