Android Question Processing Checksum

PhilipK

Member
Licensed User
Longtime User
Hi

Transferred some basic code:

B4X:
Private Function CheckCS(ByRef RawData() As Byte, _
                                  ByVal Offset As Long, _
                                  ByVal DataLength As Long, _
                                  ByVal LastArrayElement As Long) As MessageError

    Dim Checksum As Long
    Checksum = 0
    Dim DataCounter As Long

    If (Offset + DataLength - 2) < LastArrayElement Then

        For DataCounter = 0 To DataLength - 2
            Checksum = Checksum + RawData(Offset + DataCounter)
            Checksum = Checksum And &HFF
        Next

        If Checksum = RawData(Offset + DataLength - 1) Then
            CheckCS = DataOk
        Else
            CheckCS = ChecksumError
        End If

    Else
        CheckCS = InsufficientData
    End If

End Function

To B4A:

B4X:
Private Sub CheckCS(RawData() As Byte, _
                                  Offset As Long, _
                                  DataLength As Long, _
                                  ByVal LastArrayElement As Long) As Int

    Dim Checksum As Long
    Checksum = 0
    Dim DataCounter As Long

    If (Offset + DataLength - 2) < LastArrayElement Then

        For DataCounter = 0 To DataLength - 2
            Checksum = Checksum + RawData(Offset + DataCounter)
            Checksum=Bit.And(Checksum,0xFF)
        Next

        If Checksum = RawData(Offset + DataLength - 1) Then
            Return  DataOk '0
        Else
            Return  ChecksumError '1
        End If

    Else
        Return InsufficientData '2
    End If

End Function

The data bytes are signed and converted to unsigned 0 - 255

The data stream has a word format in single bytes: header, data1, data2, data n...., checksum

The header value maps to a list containing the specific word length (number of bytes) for that word

The manual says "where the checksum is greater than 255, then only the least significant byte is stored."

I'm getting 'data ok' for probably 50% of the stream. However, frequently, I am finding it is skipping chunks of the data stream, with checksum errors.

Is this due to the checksum routine not dealing with LSB?

I can't see what's going wrong. This is driving me nuts!!

Thanks in advance
 

PhilipK

Member
Licensed User
Longtime User
Mistake in code:
B4X:
If Checksum = RawData(Offset + DataLength - 1)
Should be:
B4X:
If Checksum = Bit.And(RawData(Offset + DataLength - 1),0xFF) Then
 
Upvote 0
Top