user1079065
user1079065

Reputation: 2215

unexpected result in bit shifting operation

I think the answer is straight forward but still I am not getting it.

byte a=5;
int b=10;
int c=a>>2+b>>2;
System.out.print(c);

As a>>2 is 1 and b>>2 is 2, I am expecting output to be 3 but is 0. What's the reason?

Upvotes: 4

Views: 123

Answers (1)

Denys Séguret
Denys Séguret

Reputation: 382454

It's because of operator precedence.

What you do is the same as

int c=(a>>(2+b))>>2;

You want this :

int c=(a>>2)+(b>>2);

Upvotes: 7

Related Questions