问题
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