byte[] 数组 拆包

code

package test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class Test09 {
    public static void main(String[] args) {
        byte[] bytes = new byte[]{-22, -21, 0, 0, 0, 42, 0, 7, 1, 67, 58, 92, 86, 105, 100, 101, 111, 82, 101, 99, 92, 73, 109, 97, 103, 101, 92, 50, 48, 50,
                48, 49, 50, 49, 55, 50, 50, 50, 53, 51, 53, 54, 54, 54, 46, 106, 112, 103, 96, -22, -21, 0, 0, 0, 42, 0, 8, 2, 67, 58, 92, 86, 105, 100, 101,
                111, 82, 101, 99, 92, 73, 109, 97, 103, 101, 92, 50, 48, 50, 48, 49, 50, 49, 55, 50, 50, 50, 53, 51, 53, 55, 50, 57, 46, 106, 112, 103, 98,
                -22, -21, 0, 0, 0, 42, 0, 8, 2, 67, 58, 92, 86, 105, 100, 101,
                111, 82, 101, 99, 92, 73, 109, 97, 103, 101, 92, 50, 48, 50, 48, 49, 50, 49, 55, 50, 50, 50, 53, 51, 53, 55, 50, 57, 46, 106, 112, 103, 98};

        List<byte[]> unboxing = unboxing(bytes);
        for (byte[] b1 : unboxing) {
            System.out.println(Arrays.toString(b1));
        }
    }

    private static List<byte[]> unboxing(byte[] bytes) {
        List<byte[]> list = new ArrayList<>();
        //记录每次截取的开始位置
        int start = 0;
        //int i = start + 2  跳过第一次匹配的开始位置
        for (int i = start + 2; i < bytes.length; i++) {
            if (bytes[i] == (byte) -22 && bytes[i + 1] == (byte) -21) {
                byte[] b1 = new byte[i - start];
                System.arraycopy(bytes, start, b1, 0, b1.length);
                list.add(b1);
                start = i;
            }
        }
        //截取最后一条数据
        if (start < bytes.length) {
            byte[] b1 = new byte[bytes.length - start];
            System.arraycopy(bytes, start, b1, 0, b1.length);
            list.add(b1);
        }
        return list;
    }
}

posted @ 2020-12-18 11:33  一只桔子2233  阅读(385)  评论(0编辑  收藏  举报