2

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 
1
  • 1
    To do bitwise operations, use |. + is meant for arithmetics. And use b1 & 0x7f to make the intent clearer, as you can see the real binary value to act on Commented Jul 18, 2015 at 16:03

2 Answers 2

3

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); 
Sign up to request clarification or add additional context in comments.

2 Comments

thanks. i think im going to use | operator. seems cleaner. also is there any performance difference between + and | ?
@M.kazemAkhgary On modern CPUs there would be no difference. Even older CPUs would use lookahead adders to do addition in a single cycle.
2

Missing brackets :(

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

What you had was equivalent to:

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

1 Comment

oh. i feel stupid now! i didnt know + operator has more priority than <<. thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.