在java开发中经常使用到插入数组,比如在某个元素后添加新元素,并将之后的元素后移,下面为插入数组的例子
byte[] msgTi = new byte[]{0x7e, 0x03, 0x7d, 0x00, 0x7e, 0x03, 0x7d};
Log.e("转义前", Arrays.toString(msgTi));
byte[] msgTi2 = new byte[]{0x7d, 0x02, 0x03, 0x7d, 0x01, 0x00, 0x7d, 0x02, 0x03, 0x7d, 0x01};
Log.e("转义正确", Arrays.toString(msgTi2));
Log.e("转义后", Arrays.toString(postscape(msgTi)));
private byte[] postscape(byte[] data)
{
if ((null == data) || (data.length < 2))
{
return data;
}
List<Byte> list = new ArrayList();//用来存放插入数据后新数组的集合
for (int i = 0; i < data.length; i++)
{
if (data[i] == (byte) 126)
{
list.add(Byte.valueOf((byte) 125));
list.add(Byte.valueOf((byte) 2));
} else if (data[i] == (byte) 125)
{
list.add(Byte.valueOf((byte) 125));
list.add(Byte.valueOf((byte) 1));
} else
{
list.add(Byte.valueOf(data[i]));
}
}
byte[] returndata = new byte[list.size()];
for (int i = 0; i < list.size(); i++)
{
returndata[i] = ((Byte) list.get(i)).byteValue();
}
return returndata;
}