C/cpp Checksum function to Xojo.

I have a function that needs to be converted to Xojo code.

unsigned char CheckSum(unsigned char *uBuff, unsigned char uBuffLen) {
  unsigned char i,uSum=0; 

  for(i=0;i<uBuffLen;i++) {
    uSum = uSum + uBuff[i]; 
  }

  uSum = (~uSum) + 1;
  
return uSum; 
}

Anyone quicker than me about this? I have made a prototype but it doesn’t seem to work. Hope you can do better.

Not sure if this is what you need or not

function CheckSum(uBuff() as uInt8, ubuffLen as UInt8) as Uint8
dim i as uInt8
dim uSum as integer // not uint8 as you don't know the range required
for i=0 to uBuffLen-1
usum=usum+ubuff(i)
next i
usum=(usum and &HFF) // strip off only the last 8 bits
// usum=(-usum)+1 //  this doesn't make sense as a UInt cannot be negative
return uSum
end function

using uSum as Uint8 will loop the numbers as requested
this is a version using a memory block as src

Function checksum(m as MemoryBlock) As UInt8 dim uSum,i,ubufferLen as UInt8 ubufferLen=m.Size-1 for i =0 to ubufferLen uSum=uSum+m.UInt8Value(i) next Return (not uSum)+1 End Function

the ~ is bitwise not (flips all bits) not just making it negative

It’s used for a serial and http protocol.

Should i be using BinaryStream to create a packet (from Uint8’s) then return a string using a nil encoding?
i’m in a bit of a hang because i tried the new framework but it doesn’t seem to help me it keeps crashing with unknown reason.

Perhaps it’s the encoding. But i’m not sure.

Does UInt8 overflow gracefully???
if not then this won’t work

  for i =0 to ubufferLen
    uSum=uSum+m.UInt8Value(i)
  next

Uint8 should overflow correctly

Yes they do :wink:

It works. the function is now:

Function Checksum(Data As String = "") As UInt8
  Dim uSum As UInt8 = 0
  
  If Data <> "" Then
    
    For i As integer = 0 to Len( Data )
      
      uSum = uSum + Asc( Mid( Data, i, i+1 ) )
      
    Next
    
  End If
  
  uSum = (Not uSum) + 1
  
  Return uSum
End Function

Thanks all for your input. I made it so it works for my cause.