Unexpected result in bit offset operation

I think the answer is simple, but still I do not understand it.

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

Since a>>2- 1, and b>>2- 2, I expect the output to be 3, but equal 0. What reason?

+4
source share
1 answer

This is due to the priority of the operator .

What you do is the same as

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

Do you want to:

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

Source: https://habr.com/ru/post/1548639/


All Articles