bluetooth , how to sent value 128 and over?

z80bryan

New Member
Licensed User
Longtime User
hi, I am new to b4a, just download serialExample.zip and test ok.
adding 3 button to sent data over bluetooth to PC, when value 0~127 are ok, exceed 128 will got 2 byte...why? my code here

Sub Button1_Click
If connected Then
TextWriter1.Write( Chr(49) & Chr(127)& Chr(0)& Chr(0))
TextWriter1.Flush

End If
End Sub
Sub Button2_Click
If connected Then
TextWriter1.Write( Chr(49) & Chr(0)& Chr(128)& Chr(0))
TextWriter1.Flush
End If
End Sub
Sub Button3_Click
If connected Then
TextWriter1.Write( Chr(49) & Chr(0)& Chr(0)& Chr(200))
TextWriter1.Flush
End If
End Sub


PC terminal received............

31 7F 00 00
31 00 C2 80 00
31 00 00 C3 88

please anyone tell me how to send data correctly.
 

agraham

Expert
Licensed User
Longtime User
Upvote 0

irda

Member
Licensed User
Longtime User
I have the same problem, my application can't recive values over 127 via bluetooth, how can i get a byte between 0 and 255?
 
Upvote 0

Arf

Well-Known Member
Licensed User
Longtime User
The 'Byte' type is signed 8 bit, so you will always see -128 to 127 if you examine the incoming contents of each byte.
I have to do a lot of bit manipulation and am very used to working with unsigned bytes (usually program in c++), so just last night I made a function to convert incoming (signed) Bytes to signed ints with the lowest byte holding the unsigned byte:

B4X:
Sub ByteToInt(b As Byte) As Int
    Dim a As Int
    a = b
    If a < 0 Then
        a = 256 + a
    End If
    Return a
End Sub

so if you receive 0x80 via bluetooth, the debugger shows this as -128.
Call ByteToInt() with this value and it will 0x00000080 in an signed int, which the debugger shows as 128.

There is probably a far more sophisticated way of doing it already supplied, but sometimes wrestling with the bits and bytes is a good way to reach an understanding about what your data is doing, before finding and understanding a more elegant solution.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
It is important to understand that there isn't any real difference between signed bytes and unsigned bytes.

You can write:
B4X:
Dim b As Byte = 200
You can send this byte and do whatever you need to. The value will be correct.

You can use this code to convert a signed value to unsigned value (for debugging):
B4X:
Sub SignedToUnsigned(b As Byte) As Int
 Return Bit.And(b, 0xFF)
End Sub
 
Upvote 0
Top