将两个 sbytes 组合成 int

Combine two sbytes into int

我有两个字节。我必须如何通过忽略每个字节的最高有效位来组合这两个字节。

实际上两个字节是有符号字节。所以我必须忽略最高有效位并连接 7 个剩余位。

这是我的代码和简单的例子。我得到每个字节的最后 7 位。然后我将第一个字节左移 7 并添加第二个字节。但是它没有给出正确的结果。

byte b1 = 131; // 10000011
byte b2 = 96;  // 01100000

//Ignoring most significant bit and get 7 remaining bits.
byte t1 = (byte) (b1 & 127); // 0000011 in 8-bits saved as 00000011
byte t2 = (byte) (b2 & 127); // 1100000 in 8-bits saved as 01100000

// Left shift first byte by 7. and add the second byte
// t1:  00000011 0000000
// t2:         0 1100000  +
//      00000011 1100000  =
int ut1t2 = t1 << 7 + t2; // 480 is expected but it gives 384

缺少括号:(

int ut1t2 = (t1 << 7) + t2; // returns 480!

你拥有的相当于:

int ut1t2 = t1 << (7 + t2);

你得到一个错误的结果,因为 << has lower precedence then +。您可以使用不带括号的 | 来完成(按位或运算时比 + 更常见)

int ut1t2 = t1 << 7 | t2;

或者甚至在一行中完成,像这样:

int ut1t2 = ((b1 & 127) << 7) | (b2 & 127);