Try this:

function calcChecksum(string) {
  var buf = new Buffer(string);

  // Calculate the modulo 256 checksum
  var sum = 0;
  for (var i = 0, l = buf.length; i < l; i++) {
    sum = (sum + buf[i]) % 256;
  }
  // Find the compliment
  sum = 256 - sum;

  // Convert to a two byte uppercase hex value
  var chars = sum.toString(16).toUpperCase();
  if (chars.length ==1 ) chars = "0" + chars;
  return chars;
}

On Fri, Apr 13, 2012 at 4:03 PM, Tim Caswell <[email protected]> wrote:

> Looks like you're missing the two's compliment part and the upper case
> part.
>
>
> On Fri, Apr 13, 2012 at 3:54 PM, Kevin O <[email protected]> wrote:
>
>> I am working on a node integration to a home automation device. The
>> device has an ASCII protocol that I am building a parser and a command
>> generator for.
>>
>> All of the ASCII messages that I send need to be appended with modulo 256
>> checksum. Here is the exact verbiage from the documentation.
>>
>> 2-digit checksum: This is the hexadecimal two’s complement of the
>>> modulo-256 sum of the ASCII values of all characters in the message
>>> excluding the checksum itself and the CR-LF terminator at the end of the
>>> message. Permissible characters are ASCII 0-9 and upper case A-F. When all
>>> the characters are added to the Checksum, the value should equal 0.
>>>
>>
>> I have an ASCII string of *09sw13100* that is supposed to result in hex *B8.
>> *That is what I am using as my test.
>>
>> Any ideas on how to implement this? I've tried the function below but it
>> produces the wrong output.
>>
>> function calcChecksum(asciiString) {
>>   var buf = new Buffer(asciiString);
>>   var sum = 0;
>>   for(var i=0; i<buf.length; i++) {
>>     sum = sum + buf[i];
>>   }
>>   sum = sum%256;
>>   return sum.toString(16);
>> }
>>
>> --
>> Job Board: http://jobs.nodejs.org/
>> Posting guidelines:
>> https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
>> You received this message because you are subscribed to the Google
>> Groups "nodejs" group.
>> To post to this group, send email to [email protected]
>> To unsubscribe from this group, send email to
>> [email protected]
>> For more options, visit this group at
>> http://groups.google.com/group/nodejs?hl=en?hl=en
>>
>
>

-- 
Job Board: http://jobs.nodejs.org/
Posting guidelines: 
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en

Reply via email to