2011-11-17 77 views
0

我有一個2字節的結構。如何計算這些結構數組的校驗和(例如MD5哈希)?如何計算結構數組的CRC(校驗和)?

public struct MyStruct 
{ 
    public byte Byte1; 
    public byte Byte2; 
} 

public class MyClass 
{ 
    public static byte[] ComputeChecksum(MyStruct[] myStructs) 
    { 
     // TODO: calculation. 
    } 
} 
+3

你試過了什麼?它*看起來像你應該能夠簡單地遍歷數組,將任何選擇的散列算法應用到兩個字段。另外:暴露公共字段通常是*糟糕的,並且結構上的可變(可更改)字段通常*不好... –

+0

另一方面:* [CRC](http://en.wikipedia.org/ wiki/Cyclic_redundancy_check)*,* [校驗和](http://en.wikipedia.org/wiki/Checksum)*和* [MD5](http://en.wikipedia.org/wiki/MD5)*不是一樣。 – LukeH

+0

我只是想把我的字節數組作爲MD5計算方法,它只接受byte []和MemoryStream。 –

回答

1

那麼你想要STRONG消化或只是一個快速的錯誤檢查/一致性查找值?

MD5/SHA是相當密集的操作 - 它們是圍繞幾百個字節的倍數的塊結構構建的。

fletcher和CRC32是非常有效的,並且做一個體面的工作產生一個隨機數..他們不善於隨機位位置..因此,例如,你不希望fletcher比只看只有上部或下部8位(因爲會有太少varience)..

要麼找到一個開源庫或打維基百科的各種算法。我傾向於只使用類似:

u32 hash_mystruct(mystruct[] data, u32 count) { 
     return hash((u8*)data, sizeof(mystruct) * count); 
    } 
    u32 hash(u8* data, u32 size) {  
    u32 hash = 19; 
    for (u32 i = 0; i < size; i++) { 
     u8 c = *data++; 
     if (c != 0) { // usually when doing on strings this wouldn't be needed 
     hash *= c; 
     } 
     hash += 7; 
    } 
    }