现在我有一个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数组的顺序按照以上规律颠倒一下……

解决方案 »

  1.   

    byte[] input = new byte[]{0x76, 0x50, 0x3A, (byte)0xA2, 0x11, (byte)0xAC, 0x76, 0x2F};
    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));
      

  2.   


    for(int i=0;i<a.length-1;i+=2){
    //用个temp交换a[i]和a[i+1]
    }
    如果是奇数个元素的,最后1个元素不交换
      

  3.   

    byte a[] = new byte[220];
    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];
    }蒙的..
      

  4.   

    你看这个方法行不,将a数组中的数据a[2i],a[2i+1]分别放入两个c,d两个数组中,然后将这两个数组中的数据放入b数组中。
    for(int i=0;i<(b.length)/2;i++){
        b[2*i]=d[i];
        b[2*i+1]=c[i];
    }
    没有考虑b数组的长度为寄数。
      

  5.   


    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]+" ");
    }
    }
      

  6.   

    如果我没理解错你是要每2个交换一下。我的思路是用一个栈,每2个进站出栈实现交换public static void main(String[] args) {
            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;
            
        }