1

外部ハードウェアからデータを送信または要求するハードウェア通信のアプリに取り組んでいます。必要なデータの部分を実行しました。

そして、チェックサムを計算するためにいくつかのヘルプを使用できることがわかりました。

パッケージはNSMutableDataとして作成され、送信前にバイト配列に変換されます。パッケージは次のようになります。

0x1E0x2D0x2Fデータチェックサム

16進数を2進数に変換して、1つずつ計算できると思います。しかし、それが良い考えかどうかはわかりません。これが唯一の方法なのか、それとも私が知らない組み込み関数があるのか​​を教えてください。任意の提案をいただければ幸いです。

ところで、他の投稿から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

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];

それが役に立てば幸い。

于 2013-11-04T22:02:50.073 に答える