0

我正在尝试转置 8X8 位数组。Transpose(A) 正在工作,但 Transpose(Transpose(A) 不适用于某些示例。我知道有符号字节需要做一些事情。但不知道该怎么做。下面是不工作的代码一些例子。有人可以帮我吗?

  public class  BitTranspose
  { 
    public static void main(String[] args)
    {
    byte A[] =new byte[]{'S','U','D','H','A','K','A','R'};

    System.err.println("\nPrinting A. A holds the letters SUDHAKAR");
    print(A);
    byte B[]=new byte[A.length];
    System.err.println("\nTransposing A..");
    transpose(A,1,1,B);
    print(B); // O.K        
    A=new byte[B.length];
    System.err.println("\nTransposing B..");
    transpose(B,1,1,A); 
    print(A); // Not O.K

}
public static void print(byte[] A)
{
    System.err.println();
    for(int i=0;i<A.length;i++)
    {
        System.err.println(toBinary(A[i]));
    }
}

public static String toBinary(byte b)   
    {
    String sb=new String();
    for (int i=7; i>=0; i--)
    {
         sb=sb+((b >> i)&1);
    }
    return sb;
}
static void transpose(byte A[], int m, int n, byte B[]) 
    {
       int x, y, t;          

        x = (A[0]<<24)   | (A[m]<<16)   | (A[2*m]<<8) | A[3*m]; 
        y = (A[4*m]<<24) | (A[5*m]<<16) | (A[6*m]<<8) | A[7*m]; 
        t = (x ^ (x >> 7)) & 0x00AA00AA;x = x ^ t ^ (t << 7); 
        t = (y ^ (y >> 7)) & 0x00AA00AA;y = y ^ t ^ (t << 7); 

        t = (x ^ (x >>14)) & 0x0000CCCC;x = x ^ t ^ (t <<14); 
        t = (y ^ (y >>14)) & 0x0000CCCC;y = y ^ t ^ (t <<14); 

        t = (x & 0xF0F0F0F0) | ((y >> 4) & 0x0F0F0F0F); 
        y = ((x << 4) & 0xF0F0F0F0) | (y & 0x0F0F0F0F); 
                    x = t;       
        B[0]=(byte)(x>>24);  B[n]=(byte)(x>>16);  B[2*n]=(byte)(x>>8);  B[3*n]=(byte)(x); 
        B[4*n]=(byte)(y>>24);B[5*n]=(byte)(y>>16);B[6*n]=(byte)(y>>8);  B[7*n]=(byte)(y); 
} }


下面是输出

Printing A. A Holds the letters SUDHAKAR

01010011
01010101
01000100
01001000
01000001
01001011
01000001
01010010

Transposing A..

00000000
11111111
00000000
11000001
00010100
01100000
10000101
11001110

Transposing B..

11111111
11111111
11101110
11101110
11101111
11101111
11101111
11111110

4

1 回答 1

3

问题可能出在这两行

x = (A[0]<<24)   | (A[m]<<16)   | (A[2*m]<<8) | A[3*m];
y = (A[4*m]<<24) | (A[5*m]<<16) | (A[6*m]<<8) | A[7*m];

因为 in (A[m]<<16),A[m]首先是符号扩展然后移位。A[m]如果为负数(即无符号大于 127),则会破坏高位。

尝试将它们更改为

x = (A[0]<<24)   | ((A[m]&0xFF)<<16)   | ((A[2*m] & 0xFF)<<8) | (A[3*m] & 0xFF);
y = (A[4*m]<<24) | ((A[5*m]&0xFF)<<16) | ((A[6*m] & 0xFF)<<8) | (A[7*m] & 0xFF);
于 2013-11-12T09:46:00.190 回答