M.kazem Akhgary
M.kazem Akhgary

Reputation: 19169

Combine two sbytes into int

I have two bytes. how ever i must combine this two bytes by ignoring most significant bit of each byte.

In fact two bytes are signed bytes. so i have to ignore Most significant bits and concatenate 7 remaining bits.

Here is my code with simple example. I get the last 7 bits of each byte. then i left shift first byte by 7 and add the second byte. however it does not give the correct result.

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

Upvotes: 2

Views: 109

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726869

You get a wrong result because << has lower precedence then +. You can do it with | without brackets (bitwise OR is more common than + when operating on bits)

int ut1t2 = t1 << 7 | t2;

Or even do it in one line, like this:

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

Upvotes: 3

sstan
sstan

Reputation: 36513

Missing brackets :(

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

What you had was equivalent to:

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

Upvotes: 2

Related Questions