我有一个简短的数组a像这样:

a = [ 16748,
      26979,
      25888,
      30561,
      115
    ] //in decimal

a = [ 0100000101101100,
      0110100101100011,
      0110010100100000,
      0111011101100001,
      0000000001110011
    ] //in binary


我想通过表示每个短裤的每一对位来获得另一个短裤数组b
(很难解释,但使用示例易于理解)。

因此,对于数组a,我将获得数组b

b = [ 01, 00, 00, 01, 01, 10, 11, 00,
      01, 10, 10, 01, 01, 10, 00, 11,
      01, 10, 01, 01, 00, 10, 00, 00,
      01, 11, 01, 11, 01, 10, 00, 01,
      00, 00, 00, 00, 01, 11, 00, 11
    ]


我想用伪代码这样做:

int lenght = (16/2) * a.length; //16*2 because I had short (16 bit) and I want sequences of 2 bit
short[] b = new short[length]; //I create the new array of short
int j = 0; //counter of b array
foreach n in a { //foreach short in array a
    for(int i = 16 - 2; i > 0; i-2) { //shift of 2 positions to right
        b[j] = ( (n >> i) & ((2^2)-1) ); //shift and &
        j++;
    }
}


我试图将此伪代码(假设是正确的)翻译成Java:

public static short[] createSequencesOf2Bit(short[] a) {
    int length = (16/2) * a.length;
    short[] b = new short[length];

    for(int i = 0; i < a.length; i++) {
        int j = 0;
        for(short c = 16 - 2; c > 0; c -= 2) {
            short shift = (short)(a[i] >> c);
            b[j] = (short)(shift & 0x11);
            j++;
        }
    }
    return b;
}


但是,如果我打印b[],我将无法获得想要的东西。
例如,仅考虑a (16748 = 0100000101101100)中的第一个短路。
我得到:

[1, 0, 16, 1, 1, 16, 17]


那是完全错误的。实际上我应该得到:

b = [ 01, 00, 00, 01, 01, 10, 11, 00,
      ...
    ] //in binary

b = [ 1, 0, 0, 1, 1, 2, 3, 0,
      ...
    ] //in decimal


有人能帮我吗?
非常感谢。



那很奇怪。如果我仅考虑a中的第一个短裤并打印b,则会得到:

public static short[] createSequencesOf2Bit(short[] a) {
    int length = (16/2) * a.length;
    short[] b = new short[length];

    //for(int i = 0; i < a.length; i++) {
        int j = 0;
        for(short c = (16 - 2); c >= 0; c -= 2) {
            short shift = (short)(a[0] >> c);
            b[j] = (short)(shift & 0x3);
            j++;
        }
    //}
    for(int i = 0; i < b.length; i++) {
        System.out.println("b[" + i + "]: " + b[i]);
    }
    return b;
}

b = [1 0 0 1 1 2 3 0 0 0 0 0 ... 0]


但是,如果我打印此:

public static short[] createSequencesOf2Bit(short[] a) {
    int length = (16/2) * a.length;
    short[] b = new short[length];

    for(int i = 0; i < a.length; i++) {
        int j = 0;
        for(short c = (16 - 2); c >= 0; c -= 2) {
            short shift = (short)(a[i] >> c);
            b[j] = (short)(shift & 0x3);
            j++;
        }
    }
    for(int i = 0; i < b.length; i++) {
        System.out.println("b[" + i + "]: " + b[i]);
    }
    return b;
}

b = [0 0 0 0 1 3 0 3 0 0 0 0 ... 0]

最佳答案

我怀疑主要问题是您要使用& 0x11而不是& 0x3。请记住,0x表示十六进制,因此0x11为您提供数字17,而不是3。或者您可以编写0b11来获取二进制形式的11

另外,如注释中所指出,循环条件应为c >= 0,而不是c > 0

10-05 21:52