2014-07-10 119 views
0

所以我有這樣的C代碼,我需要移植到C#:移植CRC16代碼在C C#.NET

C代碼:

uint16 crc16_calc(volatile uint8* bytes, uint32 length) 
{ 
    uint32 i; 
    uint32 j; 
    uint16 crc = 0xFFFF; 
    uint16 word; 

    for (i=0; i < length/2 ; i++) 
    { 
     word = ((uint16*)bytes)[i]; 

     // upper byte 
     j = (uint8)((word^crc) >> 8); 
     crc = (crc << 8)^crc16_table[j]; 

     // lower byte 
     j = (uint8)((word^(crc >> 8)) & 0x00FF); 
     crc = (crc << 8)^crc16_table[j]; 
    } 
    return crc; 
} 

閥塊的C#代碼:

public ushort CalculateChecksum(byte[] bytes) 
{ 
    uint j = 0; 
    ushort crc = 0xFFFF; 
    ushort word; 

    for (uint i = 0; i < bytes.Length/2; i++) 
    { 
     word = bytes[i]; 

     // Upper byte 
     j = (byte)((word^crc) >> 8); 
     crc = (ushort)((crc << 8)^crc16_table[j]); 

     // Lower byte 
     j = (byte)((word^(crc >> 8)) & 0x00FF); 
     crc = (ushort)((crc << 8)^crc16_table[j]); 
    } 

    return crc; 
} 

此C算法使用查找表crc16_table計算提供的字節的CRC16 [j]

但是,Ported C#代碼會執行n不會產生與C代碼相同的結果,我是否做錯了什麼?

回答

5
word = ((uint16*)bytes)[i]; 

讀取來自bytes兩個字節到uint16,而

word = bytes[i]; 

只是讀取單個字節。

假設你是一個小endian機器上運行,你的C#代碼可能會變成

word = bytes[i++]; 
word += bytes[i] << 8; 

或者,可能會更好,通過MerickOWA的建議

word = BitConverter.ToInt16(bytes, i++); 

請注意,您可以通過改變您的循環來避免奇怪的額外增量i

for (uint i = 0; i < bytes.Length; i+=2) 
{ 
    word = BitConverter.ToInt16(bytes, i); 
+1

或使用BitConverter.ToInt16 – MerickOWA