2's complement checksum

Post and discuss Lemur Modules.
oldgearguy
Regular
Posts:315
Joined:02 Nov 2013 11:19
2's complement checksum

Post by oldgearguy » 05 Mar 2014 11:18

I needed to calculate a 16 bit (well 15 since it's MIDI) Two's Complement checksum for a sysex message. Lemur doesn't seem to have a complement/invert (usually ~) math operator, so I had to do it the old-fashioned way. In case anyone else needs similar code, I thought I'd post it here. I know it's simple code, but if you can find it with search, it may save you the trouble of keying it in yourself.

// assumptions are -- sysex in sysexBuf; data portion spans bytes 6 through 247, checksum in byte 248
decl sum=0, i;

for (i=6; i < 248; i++)
sum += sysexBuf; // add up all the byte values
sum = 255 - (sum % 256); // longhand method of flipping the bits.
sum++; // need to add 1 for 2's complement
sum = sum & 0x7F; // mask off high bit.

sysexBuf = sum;

Post Reply