On Apr 13, 2012, at 10:54 PM, Kevin O 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);
> }
function calcChecksum(asciiString) {
var sum= 0, i= asciiString.length;
while (i--) sum+= asciiString.charCodeAt(i);
sum= (256- (sum%= 256));
return (sum<16 ? '0' : '')+ sum.toString(16).toUpperCase();
}
calcChecksum('09sw13100')
-> "B8"
--
Jorge.
--
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