Exclusive Or-ing A String

I’m writing a method to calculate a checksum byte for a block of text, which will be sent to an external piece of hardware (the manual for the hardware says, “The value of the checksum is calculated by exclusive-or the entire message.”). I’ve got the following so far:

  Dim Char(-1) As String
  Dim Checksum As Integer
  Dim N As Integer
  
  Char = Split("Test Text","")
  
  For N = 0 To UBound(Char)
    
    If Char(N) = "$" Then Continue
    
    If Checksum = 0 Then
      
      ' Yes. Set the checksum to the value.
      Checksum = Asc(Char(N))
      
    Else
      
      ' No. XOR the checksum with this character's value.
      Checksum = Checksum Xor Asc(Char(N))
      
    End If
    
  Next N
  
  Return ChrB(Checksum)

This appears to do what I want, but I don’t think it’s calculating the checksum correctly in all cases, so I’d really appreciate it if any of you kind folks could give me any pointers or suggestions for improvements?

MBS Plugin has fast functions for this:

StringXORMBS(data as string, XorMask as string, MaskOffset as integer = 0) as string

Thanks, Christian. I have the MBS Util Plugin, but I’m not sure how that method can help me here, since it seems to accept two strings and I’m not sure what the second string (XorMask) should be?

oh, sorry. Rereading your message you asked for something different.
StringXORMBS xors a string with another string.

For what you need, the code above is not that bad.

as 0 xor something is something, you can remove the if in the loop:

[code]Checksum = 0
For N = 0 To UBound(Char)

If Char(N) = "$" Then Continue

  ' No. XOR the checksum with this character's value.
  Checksum = Checksum Xor Asc(Char(N))

Next N[/code]

Thanks, Christian. I found the above code on the old RB forums whilst Googling for how to write this particular method. Removing the if in the loop simplifies the code (which is nice) and it works just the same, too. :slight_smile: