Checksum Code

From HackTheIBus

Jump to: navigation, search

Playing with Visual Basic or C/C++ and your IBus?

At some stage you'll want to generate the checksum

Here's a VB function to do it for you:

Function Calc_CheckSum(Message) As Integer
   ' calc XOR checksum for iBus protocol
   Dim n As Integer ' counter
   Dim Chk As Integer ' Checksum - will work for up to msg length of 255 bytes
   ' XOR all bytes in message
   For n = 1 To Len(Message)
       Chk = Chk Xor Asc(Mid$(Message, n, 1))
   Next
   ' get least significant byte by ANDing with FF
   ' and return it
   Calc_CheckSum = (Chk And &HFF)
End Function

And here's the same in C:

//u8 is the short form of 'unsigned char'
typedef unsigned char  u8;

//provide a pointer to a IBus frame for input
//and it will calc the XOR checksum for you

u8 IBUS_calcChecksum(u8 *pBuffer)
{

  u8 i;
  u8 checksum;
  u8 length;
 
  checksum = 0;
  length = pBuffer[1] + 1;
 
  for(i = 0; i < length; i++) {
    checksum ^= pBuffer[i];
  }
 
  return checksum;
}


For online Checksum-Calculation you can use this page:

http://www.dela.ws/bmw/chk.php

Personal tools