A question from a customer on 2s complement calculation, as an alternate to Checksum…
Note: PAC Control has a variety of commands in the “String Commands” category like “Generate Checksum on String” and “Generate Forward/Reverse CCITT/CRC-16” … but if you need something a little different, like LRC, you can always roll your own.
As the help text for “Generate Checksum on String” says:
- To calculate the LRC of a string, take the two’s complement of the checksum:
Here’s some OptoScript code to show what that example might look like in a strategy:
sTxRx = "A";
nChecksum = GenerateChecksumOnString(/*Start Value*/0, /*On String*/sTxRx);
nLRC = (255 - nChecksum) + 1; // calculate single-byte two's complement of checksum
// append that byte to the end of the string for transmitting:
sTxRx = sTxRx + chr(nLRC);
Generally, in OptoScript a 1s complement is just the bitnot of the thing to take the complement of, like we do w/setting IP addresses in this post specifically this line: ntMemMapData[1] = bitnot nIPAddress; // 1s Complement
And a 2s complement is just the 1s complement + 1. (In that help text above, they’re talking about one byte so a bitnot is the same as “subtract from 255.") Since our 32-bit (4 byte) integers are signed, you have to worry about things like sign extension on the rest of those 32-bits. So we could’ve also done, as an alternate to the last couple lines above:
// calculate the 2s complement of the checksum, and append that to the string itself
sTxRx = sTxRx + chr( 0xFF bitand ( (bitnot nChecksum) + 1 ) );
Anyway, happy coding and complementing!
-OptoMary