Juras
Juras

Reputation: 23

How to get received bytes via bluetooth in hexadecimal?

I'm trying to receive data via bt on android device. When I'm sending bytes from terminal (for example 0x10 0x20 0x30 0x40) I don't get any response (the Toast does not pop-up). I wan't to get data in hexadecimal, not as a string. Here is the code from handler:

 mHandler = new Handler() {

            public void handleMessage(android.os.Message msg)
            {if(msg.what == MESSAGE_READ){

                try {
                    byte[] readBuf = (byte[]) msg.obj;

                    Toast.makeText(MainActivity.this, readBuf[0], Toast.LENGTH_SHORT).show();

            } catch (IllegalArgumentException e) {

                e.printStackTrace();
            }

                }
            }

        };

I'm using Android Studio 2.2.3 How to display received bytes in hex form?

Edit: afted using function byteToHexString() Toast pop up only when I'm sending data as ASCII characters, nothing happens while sending as hex. I can't debug it, because Android Studio can't see my device. Modified code in handler:

byte[] readBuf = (byte[]) msg.obj;

                    String readMessage = new String(readBuf, 0, msg.arg1);
                String HexStr = null;
                    HexStr =  byteToHexString(readBuf);
                    Toast.makeText(MainActivity.this,HexStr, Toast.LENGTH_SHORT).show();

Edit 2: I can receive numbers, but only from range 0x30-0x39 - numbers assigned to chars 1-9 in ASCII. It seems like code from handler executes only while receiving ASCII numbers

Upvotes: 0

Views: 1730

Answers (1)

Luke
Luke

Reputation: 1344

You're calling makeText with readBuf[0], which is of type byte, so it gets propagated to int and the method thinks it's a resource id (Lint should issue a warning there). Instead, convert the byte array to String using DatatypeConverter#printHexBinary(byte[]) and pass that to Toast method.

Since javax packages are absent from the Android API, you can use String#format passing %2x as a format argument, and one byte you wish to format (it would be a loop iterating over all bytes).

If you care about speed however, this is as fast as it gets:

public static String byteToHexString(byte[] data) {
    StringBuilder res = new StringBuilder(data.length*2);
    int lower4 = 0x0F; //mask used to get lowest 4 bits of a byte
    for(int i=0; i<data.length; i++) {
        int higher = (data[i] >> 4);
        int lower = (data[i] & lower4);
        if(higher < 10) res.append((char)('0' + higher));
        else            res.append((char)('A' + higher - 10));
        if(lower < 10)  res.append((char)('0' + lower));
        else            res.append((char)('A' + lower - 10));
        res.append(' '); //remove this if you don't want spaces between bytes
    }
    return res.toString();
}

Upvotes: 0

Related Questions