Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 500
user1079065 Avatar asked Mar 20 '23 00:03

user1079065


1 Answers

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);
like image 178
Denys Séguret Avatar answered Mar 31 '23 04:03

Denys Séguret