无法获取完整长度的消息

Unable to get full length message

我已经实现了从字节数组中获取消息的逻辑。

public getInfo(byte[] hi) {

        type = ....

        sequence = ....

        int ack = ....

        int lastbyte = ....;

        int isUTF8byte = .....;

        actual_msg += (char) hi[CHAR1];
        actual_msg += (char) hi[CHAR2];
        actual_msg += (char) hi[CHAR3];
        actual_msg += (char) hi[CHAR4];
        actual_msg += (char) hi[CHAR5];
    }

问题是它只给我消息的前五个字符。我的意思是如果字节数组包含 Hello How are you,我只会得到 Hello 的输出。字节数组的第 3 到第 7 个字节(5 个字节)带有 char 消息。

我认为消息中剩余字符的逻辑应该在 for 循环内,因为目前我的逻辑只读取前 5 个字符。所有消息集的第 0 到第 2 个字节相同。我只关心第 3 到第 7 个字节。

我该如何实现?

我想你正在搜索这个:

byte [] subArray = Arrays.copyOfRange(bytearray, startpos, endpos);
String str = new String(subArray, StandardCharsets.UTF_8);

如果我没有正确理解你的问题,你想要的是

public String getMessage(byte[] bytes) {
    StringBuilder message = new StringBuilder(); 
    int index = 0
    while (index < bytes.length) {
        byte[] partOfMessage = Arrays.copyOfRange(bytes, index + 3, index + 7);
        message.append(new String(partOfMessage , StandardCharsets.UTF_8));
        index += 7;
    }
    return message.toString();
}