1

在对一些视频流标准进行解码时,我注意到很多情况下,整数值的位以 2-6 字节的形式提供,但由保留位分隔,如下所示:

// Specification (16 bits)
// -----------------------
// Reserved         1  bit
// Value A [6-7]    2  bit
// Reserved         2  bit
// Value A [4-5]    2  bit
// Reserved         3  bit
// Value A [0-3]    4  bit
// Reserved         2  bit

例如,值 185 (101110010xB9) 将按如下方式存储在一个两字节数组中:

01000110 00100100

我知道这很疯狂,但这就是这些人对他们的数据流进行编码的方式。可以使用以下位操作提取

int w = 0;
w |= (0x60 & data[0]) >>> 5;  // extract the first 2 bits shifted to the front
w <<= 2;                      // bump them up 2 bits for the next section
w |= (0x06 & data[0]) >>> 1;  // extract the next 2 bits shifted to the front
w <<= 4;                      // bump them up 4 bits for the last section
w |= (0x3C & data[0]) >>> 2;  // extract the last 4 bits shifted to the front

// w now will equal 10111001 (185)

我想要做的是创建一个方法,该方法将接受一个长度未定的字节数组和一个表示位掩码的 Int,这些位掩码构成我们试图从提供的规范中提取的值。像这样的东西

public static void testMethod() {

    byte[] data = new byte[] {0x46, 0x24}; // 01000110 00100100 
    int mask = 0x663C;                     // 01100110 00111100
    int x = readIntFromMaskedBytes(data, mask);

}

public static int readIntFromMaskedBytes(byte[] data, int mask) {
    int result = 0;

    // use the mask to extract the marks bits from each
    // byte and shift them appropriately to form an int

    return result;
}

我已经使用原始的“手动”方法完成了我正在从事的项目,但由于这些事件的数量及其复杂性,我不满意它尽可能干净。我很想提出一种更通用的方法来完成同样的事情。

不幸的是,当谈到移位的这种复杂性时,我仍然是一个新手,我希望有人可以就如何最好地实现这一点提供一些建议或建议。

赛拉

注意 - 请原谅上面的伪代码中的任何语法错误,它只是为了解释用例而设计的。

4

1 回答 1

1

实际上,我倾向于认为内联掩码和移位方法(如果实现比伪代码更干净一点)比尝试编写通用方法更好。对于有经验的低级 bit bashing 代码开发人员来说,阅读 mask-and-shift 代码应该没有问题。按照您提出的思路,通用方法的问题在于它的效率会大大降低......并且 JIT 编译器难以优化。

顺便说一句,这就是我编写代码的方式。

// extract and assemble xxxx from yyyy 
int w = ((0x003C & data[0]) >> 2) | 
        ((0x0600 & data[0]) >> 6) | 
        ((0x6000 & data[0]) >> 7);

编辑

不过,我仍然想了解如何将这种通用方法编码为学习练习。

像这样的东西:

public static int readIntFromMaskedBytes(int data, int mask) {
    int result = 0;
    int shift = 0;
    while (mask != 0) {
        if (mask & 1) {
            result |= (data & 1) << shift++;
        }
        data >>>= 1;
        mask >>>= 1;
    }
}

如您所见,这将需要多达 32 次循环迭代才能给出答案。对于您的示例,我会说这种方法比原始版本慢大约 10 倍。

于 2010-07-05T02:02:59.710 回答