Android Question Byte question?

wes58

Active Member
Licensed User
Longtime User
I receive data from BLE device which is in Hex Bytes (13 bytes of data).
When the received bytes are converted to hex string using ByteConverter: Dim notifyData As String = bc.HexFromBytes(data)
Displayed data look like this: 350100BF942C61B205CA18BA0B
But, when I display the value of each data byte as int using the following code:
B4X:
            Dim notifyData As String = bc.HexFromBytes(data)
            Log(notifyData.Length & " " & notifyData)
            Dim j As Int = 0
            Dim s As String
            If data.Length = 13 Then
                Dim i As Int
                For i = 0 To data.Length-1
                    s = notifyData.SubString2(j, j+2)
                    j = j+2
                    Log(i & " " & data(i) & " " & s)
                Next
            End If
The log output is:
350100BF942C61B205CA18BA0B
0 53 35
1 1 01
2 0 00
3 -65 BF
4 -108 94
5 44 2C
6 97 61
7 -78 B2
8 5 05
9 -54 CA
10 24 18
11 -70 BA
12 11 0B
So in the log you can see that for example for byte 3 - for hex value of 0xBF the byte value is displayed as -65
The same happens for byte 4, 7, 9, 11

I can convert it to receive the correct value, by checking if it is negative value:
B4X:
                    Dim k As Int
                    k = data(i)
                    If k < 0 Then
                        k = k + 256
                    End If
And then get: 256 + (- 65) = 191, which what 0xBF is.

The question is why? Why bytes values are treated as signed int?
 

OliverA

Expert
Licensed User
Longtime User
They are actually treated as signed bytes. All integers (of various bit sizes) are signed.
 
Upvote 0

wes58

Active Member
Licensed User
Longtime User
They are actually treated as signed bytes. All integers (of various bit sizes) are signed.
Yes, but integer is 4bytes and if I want to get an integer value from 1 byte (8 bits) I would expect to get 8 bits.
So the only way is to convert to a hexstring and then back to int. The conversion doesn't care about signed or not signed.
I guess that's a limitation of Java as well. In C you can define variable as "char" or "unsigned char", "int" or "unsigned int".
 
Upvote 0

OliverA

Expert
Licensed User
Longtime User
Try
B4X:
  k = Bit.And(data(i), 0xFF)
This should properly convert your byte to int as an unsigned byte
 
Upvote 0
Top