Cybergei Cybergei - 1 year ago 102
Android Question

Android get byteValue from Bluetooth data

When reading a Bluetooth sensor characteristic, the value or the measurement is stored in the characteristic value. how can I get the byte value as such:


from the sensor value?

/******** EDIT ***********/

@Vikram Recommends the following:

private void updateAdc3Values(BluetoothGattCharacteristic characteristic) {

// Convert values if needed
//double adc3 = SensorTagData.extractAdc3(characteristic);

/******** Used to get raw HEX value ********/

byte[] ADCValue3 = characteristic.getValue();
String adc3Hex = ADCValue3.toString()
.replace("[", "") //remove the right bracket
.replace("]", ""); //remove the left bracket

// Log.e("ADC3", "ADC CH3 characteristicvalue from TEST is " + adc3Hex);
// Log.i("ADC3", "ADC Last 6CH3 characteristicvalue from TEST is " + adc3Hex.substring(adc3Hex.length() - 6)); //Prints last 6 of this string

// Get UUID
String ch3 = (String.valueOf(characteristic.getUuid()));
String ch3UUID = ch3.substring(0, Math.min(ch3.length(), 8));
// Log.d("ADC3", "ADC FIRST 6CH3 characteristicvalue from TEST is " + ch3.substring(0, Math.min(ch3.length(), 8))); //Print first 6 of this string

String adc3hex6 = adc3Hex.substring(adc3Hex.length() - 6);

StringBuilder sb = new StringBuilder();
for (byte b : ADCValue3) {
if (sb.length() > 0) {
sb.append(String.format("%02x", b)); }

Log.w("ADC3", "StringBuilder " + sb);

/******** Used to get raw HEX value ********/


I have basically been using different types of output, to experiment with all of the possibilities. Using the byte[] characteristic value I am forming different types of output. Disregard the UUID, this is us just proving that the values are coming from the correct channel. So I just cut up the UUID to get the first 6 char which proves the channel it is coming from.

In the case above, the Log.i starting with ADC3 Byte Array Value, this line logs in one measurement a value of:


Then the sister log which follows after the StringBuilder is logging:


This does appear to be the correct format and value that I am looking for. Now it will be time to compare the values.

Answer Source

Transferring from comments:

OP is obtaining the byte[] from BluetoothGattCharacteristic#getValue() method.

To format the code in the required format, use the following snippet:

// Use StringBuilder so that we can go through the byte[] 
// and append formatted text
StringBuilder sb = new StringBuilder(); 

for (byte b : byteArray) { 
    if (sb.length() > 0) { 

    sb.append(String.format("%02x", b)); 
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download