How to get most significant n bits from int in java

浪尽此生 提交于 2019-12-07 16:03:59

问题


I have an int, and I would like to get the 19 most significant bits in java. I tried all sorts of methods, none of them work. Can someone please help me?


回答1:


From the 32 bit int, you want to keep the 19 most significant, so discard the 13 least; then you shift right by 13 bits, but have to get rid of the possible sign extension, by anding with a 19 bit pattern:

(myint >> 13) & 0x7ffff



回答2:


Adding to Bram's answer, you don't even need the AND if you use unsigned shift.

myInt >>> 13; will give you the 19MSB (although they're now situated in the lowest bits).




回答3:


Integer is of 4 byte i.e. 4*8 = 32 bits. So if you want to get 19th bit, you may want to try something like:

 if (myint & 0X00002000 >> 19 == 1) {
     //do something
 }


来源:https://stackoverflow.com/questions/28876549/how-to-get-most-significant-n-bits-from-int-in-java

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