简体   繁体   中英

Transposing 8XB Bits

I am trying to transpose 8X8 bit array. Transpose(A) is working but Transpose(Transpose(A) is not working for certain examples. I know there is something need to be done with signed bytes. But not sure how to do this. Below is the code which is not working on some examples. Can somebody help me?

  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); // OK A=new byte[B.length]; System.err.println("\\nTransposing B.."); transpose(B,1,1,A); print(A); // Not OK } 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); } } 


And below is the output

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

The problem is probably in these two lines

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];

Because in (A[m]<<16) , A[m] is first sign-extended and then shifted. That destroys the upper bits if A[m] is negative (ie unsigned bigger than 127).

Try changing them to

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM