Android Question negative value in the received data

Picon

Member
Licensed User
Hello everyone

I receive data via BLE and some values are received as negative values in the buffer.
I am sure that BLE receives the value hex = 0xC0 (dec = 192), but after receiving the data, I have 0xFFFFFFC0 in the buffer, which gives dec = -64
How to get the correct data, i.e. 0xC0?

I will be grateful for any advice
Thank you
 

emexes

Expert
Licensed User
You can convert signed bytes (-128 to +127) to unsigned (0 to 255) using bitwise And eg:

B4X:
For I = 12 to 255 step 15    'start at 12 so passes through 0xC0
    Dim B As Byte = I
    Dim UnsignedValue As Int = Bit.And(B, 0xFF)    'converts signed Byte value to unsigned
    Log(I & Tab & Bit.ToHexString(I) & Tab & B & Tab & UnsignedValue)
Next
Log output:
Waiting for debugger to connect...
Program started.
12    c     12    12
27    1b    27    27
42    2a    42    42
57    39    57    57
72    48    72    72
87    57    87    87
102   66    102   102
117   75    117   117
132   84    -124  132
147   93    -109  147
162   a2    -94   162
177   b1    -79   177
192   c0    -64   192
207   cf    -49   207
222   de    -34   222
237   ed    -19   237
252   fc    -4    252

If you take the variable that contains -64 (could be 8-bit Byte 0xC0, or 16-bit Short 0xFFC0, or 32-bit Int 0xFFFFFFC0) and do a Bit.And(variable, 0xFF) on it, it will return just the lower 8 bits 0x000000C0 ie 0xC0 ie 192.
 
Last edited:
Upvote 1

Picon

Member
Licensed User
You can convert signed bytes (-128 to +127) to unsigned (0 to 255) using bitwise And eg:

B4X:
For I = 0 to 255 step 15
    Dim B As Byte = I
    Dim UnsignedValue As Int = Bit.And(B, 0xFF)    'converts signed Byte value to unsigned
    Log(I & Tab & B & Tab & UnsignedValue)
Next

If you take the variable that contains -64 (could be 8-bit Byte 0xC0, or 16-bit Short 0xFFC0, or 32-bit Int 0xFFFFFFC0) and do a Bit.And(variable, 0xFF) on it, it will return just the lower 8 bits 0x000000C0 ie 0xC0 ie 192.
Thank you very much!!
I'm still learning and there's so much I don't know yet.
I wish you all the best!!
 
Upvote 0
Top