Android Question get bytes from short integer

Alvsky

Member
Licensed User
Longtime User
Hi All
I have a conversion problem.
I have a value from 0 to 1023 stored in Short integer and I need to extract high and low byte from it and store it as Char so I tried following:

B4X:
Sub Globals
    ...
    Dim servo1() As Short 
    Dim servo1H As Char
    Dim servo1L As Char
    ...
End Sub

Sub btnSend_Click
   
    servo1L = Bit.And(servo1(0),0xFF)
    servo1H = Bit.ShiftRight(Bit.And(servo1(0),0xF00), 8)

    Log(servo1(0)&": "&int2Bin(servo1(0),16))
    Log ("High byte: "&servo1H&" Low byte: "&servo1L)

End Sub

results I get in Log are following:


1023: 0000001111111111
High byte: 3 Low byte: 2
771: 0000001100000011
High byte: 3 Low byte: 3
669: 0000001010011101
High byte: 2 Low byte: 1
** Activity (main) Pause, UserClosed = false **

So.. my question is what am I doing wrong?

Thanks
 

Alvsky

Member
Licensed User
Longtime User
Thanks for this simple solution.
Only thing is that it returns lower byte b(1) as signed and for s=130 it returns:
High byte: 0 Low byte: -126

This can be solved using your ToUnsigned Sub which gives output:
High byte: 0 Low byte: 130

Si if someone will need, here is all routine:

B4X:
Sub ToUnsigned(b As Byte) As Int
  Return Bit.And(0xFF, b)
End Sub

Sub btnSend_Click
   
   Dim bc As ByteConverter
   Dim s As Short = 130

   Dim g() As Byte = bc.ShortsToBytes(Array As Short(s))
   Log ("High byte: "&g(0)&" Low byte: "&(g(1)))
   Log ("High byte: "&g(0)&" Low byte: "&ToUnsigned(g(1)))

End Sub
and output:

High byte: 0 Low byte: -126
High byte: 0 Low byte: 130
 
Upvote 0
Top