Wun
Wun

Reputation: 6381

What the value mean convert from string to Hex for BLE?

I am developing BLE in Android.

And I try to send string value to BLE device

It seem the string need to convert to byte before send to BLE device.

I found some code like the following , the code seems can convert the string value to byte.

private byte[] parseHex(String hexString) {
        hexString = hexString.replaceAll("\\s", "").toUpperCase();
        String filtered = new String();
        for(int i = 0; i != hexString.length(); ++i) {
            if (hexVal(hexString.charAt(i)) != -1)
                filtered += hexString.charAt(i);
        }

        if (filtered.length() % 2 != 0) {
            char last = filtered.charAt(filtered.length() - 1);
            filtered = filtered.substring(0, filtered.length() - 1) + '0' + last;
        }

        return hexStringToByteArray(filtered);
    }

     public static byte[] hexStringToByteArray(String s) {
            int len = s.length();
            byte[] data = new byte[len / 2];
            for (int i = 0; i < len; i += 2) {
                data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                                     + Character.digit(s.charAt(i+1), 16));
            }
            return data;
        }

    private int hexVal(char ch) {
        return Character.digit(ch, 16);
    }

I call the above function before send the string to the BLE device like the following code.

byte[] value = parseHex(text);
mCharacteristic.setValue(value);
mBluetoothGatt.writeCharacteristic(mCharacteristic);

The BLE device will show the value which I have send to it. But the value is strange and I did not under stand what it mean.

The value what I send and the value show from BLE device are like the following.

Send             BLE Show
  1                 1
  2                 2
  9                 9
  10                16
  11                17
  20                32
  30                48
  40                64
  70                112
  90                144
  99                153
  100               16

I did not understand what the value mean show on BLE device... Does someone help me ?

Upvotes: 1

Views: 1882

Answers (1)

ianhanniballake
ianhanniballake

Reputation: 199795

You are sending the hex values, which is a base 16 system, but your BLE Show values are in decimal.

Therefore sending 10 in hex is 1*16+0*1=16 in decimal. Similarly, 99 is 9*16+9*1=153 in decimal

Upvotes: 2

Related Questions