Issue
I'm developing an app which receives a continuous flow of data using ble, at this moment I properly read the flow sent by the device, but in fact I don't know how to interpret it.
This is my onCharacteristicChanged function
override fun onCharacteristicChanged(
gatt: BluetoothGatt,
characteristic: BluetoothGattCharacteristic?
) {
if (characteristic != null && characteristic.properties == BluetoothGattCharacteristic.PROPERTY_NOTIFY) {
Log.e(TAG, "**THIS IS A NOTIFY MESSAGE")
}
if (characteristic != null) {
data = characteristic.value
Log.e("onCharacteristicChanged", "Datos:")
Log.e("onCharacteristicChanged", "$data")
val dataparsed = data?.joinToString ( " : " )
Log.e("onCharacteristicChanged", "$dataparsed")
broadcastUpdate("com.np.lekotlin.ACTION_DATA_AVAILABLE")
}
}
This function is called every time the device sends me some info, returning an exit like this one:
Where we can see two interpretations of the same data
The data without treatment (the bytearray): [B@ **** And the data after the joinToString (function I thought it would help me casting into hexa): ** : **: **: **: **: **: **: **: **: ** <-- But here there are negative numbers!!
My problem comes when I compare this output with the returned by another software I am using, CySmart
Which returns me something like
07:94:02:5A:56:00:76:35:00:00
07:2F:02:5F:45:00:B0:36:00:00
07:E4:01:50:47:00:6D:37:00:00
07:0C:02:53:4A:00:56:38:00:00
This output obviously follows a pattern, the first 7 and the 2 last group of 0s, for example but the negative numbers are baffling me.
So, in summary, my question is, exist any native way in kotlin to cast from bytearray to hexa? (without negative numbers) In case I'm already casting it properly do you figure how can I treat, or which is the patron with the negatives numbers? It seems like 2's complement or something like that, but I don't know it surely.
Lots of thanks in advise.
Solution
As others have already mentioned having a negative number in a byte array only means that the number is larger than 127.
As for your question on how to display them as hex, you can use the built-in string formatting functions. You can add a transform block to your joinToString
call which can convert your byte to a hex string:
val dataparsed = data?.joinToString ( " : " ) { "%02x".format(it) }
This way your output will be formatted correctly.
Answered By - pshegger
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.