-1

I'm making an Android app that communicates with bluetooth device. I'm writing a specific message to chosen characteristic as follows:

byte[] clearDataset = new byte [0x0A];
Log.d("uploadDataset", "Message: " + Converters.byteArrayToHexString(clearDataset, 0, clearDataset.length));
writeCharacteristic(Converters.byteArrayToHexString(clearDataset, 0, clearDataset.length), Constants.DIAG_WRITE);

My conversion function looks like this:

public static String byteArrayToHexString(byte[] bytes, int startingByte , int endingByte) {
        byte[] shortenBytes = Arrays.copyOfRange(bytes, startingByte, endingByte);
        final byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
        byte[] hexChars = new byte[shortenBytes.length * 2];
        for (int j = 0; j < shortenBytes.length; j++) {
            int v = shortenBytes[j] & 0xFF;
            hexChars[j * 2] = HEX_ARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }

        StringBuilder output = new StringBuilder();

        for (int i = 0; i < new String(hexChars, StandardCharsets.UTF_8).length(); i += 2) {
            String str = new String(hexChars, StandardCharsets.UTF_8).substring(i, i + 2);
            output.append((char) Integer.parseInt(str, 16));
        }

        return output.toString();
    }

I'm trying to figure out why in this case my conversion output looks like this:

D/uploadDataset: Message: ��������������������

It is strange, because the same conversion function works perfectly fine when I'm using it to translate the values that I'm receiving as bluetooth notification. Any suggestions where the problem lies are welcome

1 Answers1

1

Throw away your StringBuilder stuff.

 return new String(hexChars);
blackapps
  • 8,011
  • 2
  • 11
  • 25
  • Strangely it works, but could you tell me why in this case I need to get rid of StringBuilder? I assume it is the same situation when I'm receiving the value from characteristic in onCharacteristicChanged callback. In this StringBuilder is necessary for proper conversion – Julian Modlinski Dec 31 '21 at 13:13
  • I dont know. Probably because you are messing around with charsets. You dont need charsets at all using only "0123456789ABCDEF" – blackapps Dec 31 '21 at 14:29
  • Have a look at https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java And the answer with 267 points. Only five code lines are enough. It makes no sense that you have different results when receiving from somewhere els. – blackapps Dec 31 '21 at 14:37
  • Cool, thank you for your help and time :) – Julian Modlinski Dec 31 '21 at 15:01