在对一些视频流标准进行解码时,我注意到很多情况下,整数值的位以 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 (10111001
或0xB9
) 将按如下方式存储在一个两字节数组中:
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;
}
我已经使用原始的“手动”方法完成了我正在从事的项目,但由于这些事件的数量及其复杂性,我不满意它尽可能干净。我很想提出一种更通用的方法来完成同样的事情。
不幸的是,当谈到移位的这种复杂性时,我仍然是一个新手,我希望有人可以就如何最好地实现这一点提供一些建议或建议。
赛拉
注意 - 请原谅上面的伪代码中的任何语法错误,它只是为了解释用例而设计的。