Android Question 16 bit word variable?

techknight

Well-Known Member
Licensed User
Longtime User
Is there a way to define a 16-bit/word variable?

Basically, I am trying to perform what is called a "Checksum-16" Which is basically all the bytes in an array, added together into a 16-bit word variable.

any ideas?
 

JordiCP

Expert
Licensed User
Longtime User
Just use a B4A integer (32bit) and then mask it with 0xFFFF

Also, if you want to add the bytes as unsigned values, you must check their value, since in B4A they are signed.
(I mean, 0x80 as a B4A byte is -128 instead of 128)

Something similar to
B4X:
Sub calcChecksum16( myData() as Byte ) as Int
  Dim myCheck as int  'use a 32-bit integer
  myCheck =0 'or initial value
  for k=0 to myData.length-1
    If myData(k)>0 then
      myCheck=myCheck+myData(k)
    Else
      myCheck=myCheck-myData(k)
    End if
  next
  myCheck=Bit.And(myCheck,0xFFFF)
  return ( myCheck )
End Sub


--EDIT--
Oops! I have just seen that "Short" also exists as a data type in B4A. But anyway the above should work
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
So how do I fix that?
My 2 cent (not really sure it helps reading your data):
Use RandomAccessFile to read the file (or parts from it)
B4X:
   Dim raf As RandomAccessFile
   raf.Initialize3(data, True) 'change the endianess if the version number is incorrect
   BuildVersionNumber = raf.ReadShort(0)
   PacketType = raf.ReadSignedByte(2)
   RaceStateFlags = raf.ReadUnsignedByte(10)
 
Upvote 0
Cookies are required to use this site. You must accept them to continue using the site. Learn more…