Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java bit operators

I came across this piece of code in java and will be delighted if someone can explain the logic to me.

public boolean name(int n) {
   return ((n >> n) & 1L) > 0; 
}

this is a kind of check operation I guess but what boolean value will this code return. And is there an alternative to this code. I am trying my best to understand bit manipulation in java.

like image 492
faisal abdulai Avatar asked Sep 01 '26 06:09

faisal abdulai


1 Answers

That's a bizarre piece of code. It checks whether the number n, having been shifted right n % 32 bits, is odd.

The first non-negative values which pass are 37 (100101 in binary), 70 (1000110 in binary), and 101 (1100101 in binary).

I doubt that it actually works as the original coder intended it to - it doesn't obviously signify anything useful (and the method name of name is pretty unhelpful...)

like image 182
Jon Skeet Avatar answered Sep 03 '26 21:09

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!