简体   繁体   English

字节数组到字符串的转换

[英]Byte array to string conversion

I'm making an Android app that communicates with bluetooth device.我正在制作一个与蓝牙设备通信的 Android 应用程序。 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:我的转换 function 看起来像这样:

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:我试图弄清楚为什么在这种情况下我的转换 output 看起来像这样:

D/uploadDataset: Message: �������������������� D/uploadDataset:消息:��������������������

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.这很奇怪,因为相同的转换 function 在我使用它来转换我作为蓝牙通知接收的值时工作得很好。 Any suggestions where the problem lies are welcome欢迎提出问题所在的任何建议

Throw away your StringBuilder stuff.扔掉你的 StringBuilder 东西。

 return new String(hexChars);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM