2012-07-24 109 views
1

我正在開發一個我發送或需要外部硬件數據的硬件通信應用程序。我有要求的數據部分完成。如何計算二進制校驗和?

而我只是發現我可以使用一些幫助來計算校驗和。

將包創建爲NSMutableData,然後在發送之前將其轉換爲Byte Array。 一個包看起來是這樣的:

0X1E 0x2D值爲0x2F數據校驗和

我想我可以十六進制轉換成二進制計算它們一個接一個。但我不知道這是不是一個好主意。請讓我知道這是否是唯一的方法,或者有一些內置函數我不知道。 任何建議將不勝感激。

順便說一句,我剛剛從其他人的帖子找到C#的代碼,我會盡量讓它在我的應用程序中工作。如果可以的話,我會分享給你。仍然任何建議將不勝感激。

package org.example.checksum; 

public class InternetChecksum { 

    /** 
    * Calculate the Internet Checksum of a buffer (RFC 1071 -  http://www.faqs.org/rfcs/rfc1071.html) 
    * Algorithm is 
    * 1) apply a 16-bit 1's complement sum over all octets (adjacent 8-bit pairs [A,B], final odd length is [A,0]) 
    * 2) apply 1's complement to this final sum 
    * 
    * Notes: 
    * 1's complement is bitwise NOT of positive value. 
    * Ensure that any carry bits are added back to avoid off-by-one errors 
    * 
    * 
    * @param buf The message 
    * @return The checksum 
    */ 
    public long calculateChecksum(byte[] buf) { 
int length = buf.length; 
int i = 0; 

long sum = 0; 
long data; 

// Handle all pairs 
while (length > 1) { 
    // Corrected to include @Andy's edits and various comments on Stack Overflow 
    data = (((buf[i] << 8) & 0xFF00) | ((buf[i + 1]) & 0xFF)); 
    sum += data; 
    // 1's complement carry bit correction in 16-bits (detecting sign extension) 
    if ((sum & 0xFFFF0000) > 0) { 
    sum = sum & 0xFFFF; 
    sum += 1; 
    } 

    i += 2; 
    length -= 2; 
} 

// Handle remaining byte in odd length buffers 
if (length > 0) { 
    // Corrected to include @Andy's edits and various comments on Stack Overflow 
    sum += (buf[i] << 8 & 0xFF00); 
    // 1's complement carry bit correction in 16-bits (detecting sign extension) 
    if ((sum & 0xFFFF0000) > 0) { 
    sum = sum & 0xFFFF; 
    sum += 1; 
    } 
} 

// Final 1's complement value correction to 16-bits 
sum = ~sum; 
sum = sum & 0xFFFF; 
return sum; 

    } 

} 
+0

爲什麼不使用簡單的普通C CRC32? http://www.csbruce.com/~csbruce/software/crc32.c – 2012-07-24 21:41:41

+0

@ H2CO3嗨,你能稍微詳細地向我解釋一下嗎?我試圖閱讀它,但仍不太清楚如何使用它。謝謝。 – user1491987 2012-07-24 22:27:27

+0

@只需使用名爲CalculateCRC32MemoryBuffer的函數 - 其餘部分是噪聲。 – 2012-07-25 05:25:48

回答

1

當我在一年前發佈這個問題時,我對Objective-C仍然很陌生。事實證明,這件事很容易做到。

計算校驗和的方式取決於通訊協議中如何定義校驗和。在我的情況下,校驗和只是所有以前發送的字節或您想要發送的數據的總和。

所以,如果我有一些有5個字節的NSMutableData * CMD:

爲0x10 0x14的0xE1 0xA4 0x32

校驗和是爲0x10 + 0x14的+ 0xE1 + 0xA4 + 0x32

所以最後一個字節總和是01DB,校驗和是0xDB。

代碼:

//i is the length of cmd 
- (Byte)CalcCheckSum:(Byte)i data:(NSMutableData *)cmd 
{ Byte * cmdByte = (Byte *)malloc(i); 
    memcpy(cmdByte, [cmd bytes], i); 
    Byte local_cs = 0; 
    int j = 0; 
    while (i>0) { 
     local_cs += cmdByte[j]; 
     i--; 
     j++; 
    }; 
    local_cs = local_cs&0xff; 
    return local_cs; 
} 

要使用它:

Byte checkSum = [self CalcCheckSum:[command length] data:command]; 

希望它能幫助。

+0

我以其他方式使用校驗和:http://stackoverflow.com/questions/19772650/checksum-of-a-hex-string-in-objective-c。你能看看嗎? – 2013-11-05 04:24:05