Android Question Xor Checksum HELL!!!

kimble01

Member
Licensed User
Longtime User
I have mangled this and Mangled This...I cannot figure out what I'm doing wrong.

I'm writing software to read and write commands to a device. The device has a message format of:
<start><command><length><Data1><Datan><BCC CheckSum><end>
and this is an actual string from the device:
024A033030317B03

So 02 is the start bit, 4A is the command, 03 is the length of the data, the next 3 bytes are the data, then 7B is the checksum and then the end bit.

The instructions from the documentation for checksum say:
Block Checksum Character: XOR of all Characters from start to last character of data.

Here is the code I have now which is close but no cigar:
B4X:
Sub GetCheckSum(MyData As String) As String
    Dim CRC = 0 As Int
    If Not(MyData.StartsWith("02")) Then
        MyData = "02" & MyData
    End If
    Try
        Dim CRC = 0 As Int
        Do While MyData.Length >= 2
            CRC = Bit.Xor(CRC, Bit.ParseInt(MyData.SubString2(0, 2), 16))
            MyData = MyData.SubString(2)
        Loop
        Dim tmp(1) As Byte
        tmp(0) = CRC
        Dim tmpStr = conv.HexFromBytes(tmp) As String
        Return tmpStr
    Catch
        Log("Couldn't convert! Error was: " & LastException.Message)
        Return("00")
    End Try
   
End Sub

Checksum is 123

This code produces:
Computed Checksum 4B (75)

What am I doing wrong?!!
 

mc73

Well-Known Member
Licensed User
Longtime User
I think that the code is correct.
I notice that in your example, the correct checkSum should be 7a instead of 7b. Can you give the actual string used to get 123 instead of 4b?
 
Upvote 0

kimble01

Member
Licensed User
Longtime User
I think that the code is correct.
I notice that in your example, the correct checkSum should be 7a instead of 7b. Can you give the actual string used to get 123 instead of 4b?

Thanks for quick reply!
This is the code used to report the Checksum:
B4X:
Log("Checksum " & curbyte  & " Computed Checksum " & CRC)

where curbyte is the current byte of the conv.HexFromBytes(Incoming) result.

In case that's confusing, using the above example string a byte array is created with the
B4X:
conv.HexToBytes("024A033030317B03")

and received in the with the code:
B4X:
Sub GetResponseString(Incoming() As Byte) As String
   Dim tempstring = conv.HexFromBytes(Incoming) As String
   ParseMessage(Incoming)
   Return tempstring
End Sub
and then the individual bytes are spooled-through with a For loop.
 
Upvote 0
Top