Negative logical shift

女生的网名这么多〃 提交于 2019-11-29 02:45:45

It's because when you are shifting a 32-bit int, it just takes the last 5 bits of the shift distance. (i.e. mod 32), so -1 mod 32 = 31, so you are shifting right by 31 bits. When you are shifting a negative number (the beginning bits of which are all 1s), you end up with a 1. Similarly, shifting right by -2 is shifting right by 30 bits, etc. If you shift a long, it would take 6 bits of the shift distance. See here for the specification of how the shift operators work: http://docs.oracle.com/javase/specs/jls/se8/html/jls-15.html#jls-15.19

polygenelubricants

Java masks the right operand based on the size of the left operand.

For a 32-bit int i,

i << N   --> i << (N mod 32)

For a 64-bit long num,

num << N --> num << (N mod 64)

This masking of the shift count operand also applies to >> and >>>.

See also

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!