Skip to content
Advertisement

Byte array to string conversion

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

Advertisement

Answer

Throw away your StringBuilder stuff.

 return new String(hexChars);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement