1

我正在开发一个硬件通信应用程序,我从外部硬件发送或需要数据。我已经完成了所需的数据部分。

我刚刚发现我可以使用一些帮助来计算校验和。

一个包被创建为 NSMutableData,然后在发送之前将其转换为字节数组。一个包看起来像这样:

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;

  }

}
4

1 回答 1

1

When I post this question a year ago, I was still quite new to Objective-C. It turned out to be something very easy to do.

The way you calculate checksum is based on how checksum is defined in your communication protocol. In my case, checksum is just the sum of all the previous bytes sent or the data you want to send.

So if I have a NSMutableData *cmd that has five bytes:

0x10 0x14 0xE1 0xA4 0x32

checksum is the last byte of 0x10+0x14+0xE1+0xA4+0x32

So the sum is 01DB, checksum is 0xDB.

Code:

//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;
}

To use it:

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

Hope it helps.

于 2013-11-04T22:02:50.073 回答