现在我有一个byte数组 byte a[] = new byte[220];
a 中 是220个字节,比如它的前8个字节是 76 50 3A A2 11 AC 76 2F
我现在我要把顺序改为: 50 76 A2 3A AC 11 2F 76就是第一个和第二个顺序换一下,第三字节和第四个字节顺序换一下,依此类推…… 写一个方法,使我得到得到的byte数组 b 和 a byte数组的顺序按照以上规律颠倒一下……
a 中 是220个字节,比如它的前8个字节是 76 50 3A A2 11 AC 76 2F
我现在我要把顺序改为: 50 76 A2 3A AC 11 2F 76就是第一个和第二个顺序换一下,第三字节和第四个字节顺序换一下,依此类推…… 写一个方法,使我得到得到的byte数组 b 和 a byte数组的顺序按照以上规律颠倒一下……
for (int i=0; i<input.length ; i++){
if (i%2==0){
byte temp = input[i];
input[i] = input[i+1];
input[i+1] = temp;
}
}
for (byte b: input)
System.out.println(Integer.toHexString(b & 255));
for(int i=0;i<a.length-1;i+=2){
//用个temp交换a[i]和a[i+1]
}
如果是奇数个元素的,最后1个元素不交换
byte b[] = new byte[220];
for(int i = 0 ; i < a.length ; i = i+2)
{
b[i] = a[i+1];
b[i+1] = a[i];
}蒙的..
for(int i=0;i<(b.length)/2;i++){
b[2*i]=d[i];
b[2*i+1]=c[i];
}
没有考虑b数组的长度为寄数。
public void changeByteComposition(byte a[])
{
byte b[] = new byte[a.length];
if(a.length % 2 == 1)
{
b[b.length-1] = a[a.length-1];
}
for(int i = 0 ; i < a.length - (a.length%2) ; i = i+2)
{
b[i] = a[i+1];
b[i+1] = a[i];
}
for(int i = 0 ; i < a.length ; i++)
{
System.out.print(a[i]+" ");
}
System.out.println();
for(int i = 0 ; i < b.length ; i++)
{
System.out.print(b[i]+" ");
}
}
byte[] a = new byte[4];
a[0]= 1;
a[1]= 2;
a[2]= 3;
a[3]= 4;
System.out.println(Arrays.toString(a));
List<Byte> result = new ArrayList<Byte>();
result = exchange(a);
System.out.println(Arrays.asList(result));
}
private static List<Byte> exchange(byte a[]){
Stack<Byte> stack = new Stack<Byte>();
List<Byte> result = new ArrayList<Byte>();
for (int i = 0; i < a.length; i+=1) {
if(stack.size()==2){
result.add(stack.pop());
result.add(stack.pop());
}else{
stack.push(a[i]);
stack.push(a[i+1]);
}
}
return result;
}