shifting bits DOES NOT WRAP
Originally posted by Harwinder Bhatia:
1. Now I kind of understand the concept of masking. Now could somebody please explain me why the mask of 0x1f is applied to the RH operand, if the left hand operand of a shift expression is of type int? I think this is deduced from something ... I just want to understand what that is?
Originally posted by Harwinder Bhatia:
2.
If this is the case, how does 1 << 33 equal to 2?
According to your explanation, it should be 0, because in the following expression:
0000 0000 0000 0000 0000 0000 0000 0001 << 33
1 should just fall off at the 32nd shift, then how come the result is 2?
I'm really confused here.
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
Prints 31,0. The expression (1 & 0x1f) is equal to (0xffffffff & 0x1f), and both are equal to the hex value 0x1f or decimal 31. The expression (8 << 1) is equivalent to (8 << 0xffffffff). If the left hand operand of a shift expression is of type int, then the right hand operand is implicitly masked with the value 0x1f. In other words, the expression (8 << 1) is equivalent to (8 << (1 & 0x1f)). By replacing 1 with the hexadecimal representation we have (8 << (0xffffffff & 0x1f)). By evaluating the right hand operand we have (8 << 31). When 8 is shifted 31 bits to the left, the result is zero since the only nonzero bit is lost as it is shifted beyond the most significant bit of the int data type.
Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
It's weird that we cook bacon and bake cookies. Eat this tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/ThreadBoostfeature
