Android Question [SOLVED] Checksum calculation

Lello1964

Well-Known Member
Licensed User
Longtime User
I have to calculate checksum using this rules :

To ensure that a request or reply packet was received with no errors, both layers use
a special field: the checksum. Checksum is always the last field in the packet in all
cases of packet transmittances. It also must be separated from the previous field
using the slash (/). Checksums are always a 2-digitdecimal values and represent the
modulo 100 of the 8-bit sum of all data octets in the packet except any control codes
or the 2-digits checksum itself but including the field separators. All field
separators are calculated in the checksum.


this is example in C:

'C' example:
BYTE CalcChecksum(BYTE *packet)
{
BYTE sum = 0;
int checklength = strlen(packet) - 2;
while(checklength--) sum += (BYTE) (*packet++);
return( (sum % 100) );

this is pseudo code example :

Pseudo code example:
Function Calculate_Checksum( parameter data_packet ) Returns BYTE
Begin
12
Declare CALCSUM, I as BYTE
CALCSUM = 0
For I = 0 to stringlength( data_packet ) - 2 Do
CALCSUM = CALCSUM + ASCII( data_packet[ I ] ) )
Next I
CALCSUM = CALCSUM mod 100
Return CALCSUM
End

those are some string and their checksum in Red color :

00/00/02/75
00/00/06/79
00/00/02/061121/002027/99

q/1/00


this is my B4X code

Checksum:
    Dim Stringa As String  = "q/1/"
 
    Dim x As Int
    For i = 0 To Stringa.Length -1
        x = x + Asc(Stringa.CharAt(i))
    Next

    x = x Mod 100
 
    Log(x)  ' = 56

checksum of "q/1/" return 56, but must be : 00

I don't kwow why ?



SOLVED :


Must be :

B4X:
x = x Mod 256    ' = 0
x = x Mod 100

better :

x =(x Mod 256) Mod 100
 
Last edited:

Star-Dust

Expert
Licensed User
Longtime User
B4X:
Public Sub CheckSum(S As String) As String
    Dim Sum As Int = 0
 
    For i=0 To S.Length-1
        Sum=Bit.And (0xff,Sum + Asc(s.CharAt(i)))
    Next
 
    Sum = Sum Mod 100
 
    Return $"$2.0{Sum}"$
End Sub

B4X:
Log(CheckSum("00/00/02/"))
Log(CheckSum("00/00/06/"))
Log(CheckSum("00/00/02/061121/002027/"))
Log(CheckSum("q/1/"))

Waiting for debugger to connect...
Program started.
75
79
99
00
 
Upvote 1
Top